不替换某些变量

时间:2011-07-25 10:16:10

标签: perl

以下代码部分按预期工作......

create table todel (id int not null auto_increment, name varchar(100), primary key (id));
insert into todel values (NULL, '24');
select @myid:=last_insert_id();
insert into todel values (NULL, @myid);

mysql> select * from todel;
+----+------+
| id | name |
+----+------+
|  1 | 24   |
|  2 | 1    |
+----+------+

但是当我尝试将其包装在perl代码中时,相同的代码不起作用。

vi myperl.pl

#!D:\Perl\bin\perl

open (output_file, ">myperl.txt");
@Program_ID = '24';
print output_file
"create table todel (id int not null auto_increment, name varchar(100), primary key (id));
insert into todel values (NULL, '@Program_ID');
select @myid:=last_insert_id();
insert into todel values (NULL, '@myid');";

close(output_file);

它生成如下所示的代码。缺少mysql变量名@myid。

# cat myperl.txt
create table todel (id int not null auto_increment, name varchar(100), primary key (id));
insert into todel values (NULL, '24');
select :=last_insert_id();
insert into todel values (NULL, '');

如何让perl知道我不想替换mysql变量?我想要替换@Program_ID变量。

4 个答案:

答案 0 :(得分:3)

尝试

insert into todel values (NULL, '\@Program_ID');
select \@myid:=last_insert_id();
insert into todel values (NULL, '\@myid');";

答案 1 :(得分:1)

您需要转义@中的@myid,否则Perl会将其视为名为myid的数组。

答案 2 :(得分:1)

在你的print语句之上,放my @myid = 'a';并注释掉glob output_file,如下所示:

print # output_file
    "create...

exit 0;放在print语句之后,如下所示:

...
insert into todel values (NULL, '@myid');";
exit 0;

你应该看到这个:

create table todel (id int not null auto_increment, name varchar(100), primary key (id));
insert into todel values (NULL, '24');
select a:=last_insert_id();
insert into todel values (NULL, a);

因此,您应该看到数组 @myid的内容替换了字符串@myid

现在注释掉@myid的声明,并将其插入脚本的顶部:

use strict;
use warnings;

然后运行它。在5.12下你应该看到:

Possible unintended interpolation of @myid in string at - line nn.
Possible unintended interpolation of @myid in string at - line nn.
Global symbol "@myid" requires explicit package name at - line nn.
Global symbol "@myid" requires explicit package name at - line nn.
Execution of - aborted due to compilation errors.

你认为如果你曾经使用strict,这些错误会告诉你足够的吗?即使你不理解“插值”,谷歌搜索“perl插值”也会有很大的帮助。

现在,取消注释声明my @myid = 'a';,当您运行它时,您将看到与以前相同的输出,但没有错误消息。

这意味着当Perl在双引号情况下看到$@时(实际上,查找“perl interpolation”或perldoc perlop)它替换该字符串中的同名变量。它借鉴了UNIX世界内插引号的想法(")  和非插值引号(')并且在插值引用情形中,你必须转义符号('$''@'),然后Perl将它视为文字字符。

你可以做的另一件事是纠正整个混乱是使用非插值报价运算符。由于您在SQL中使用单引号,我们不能仅使用单引号来避免插值。相反,我们可以使用q运算符。将q{放在SQL的顶部,将}放在底部,如下所示:

print output_file
    q{create ...
    ...
    insert into todel values (NULL, @myid);
    };

真的,点击perldoc链接。

答案 3 :(得分:0)

就像其他人所说的那样,@让解释者感到困惑。这就是为什么如果它不包含任何变量插值,它(IMO)是一个单引号字符串的好习惯。