如何转义 Perl 字符串中类似代码的内容?
$i=1; while($i<3) { 打印<< “EOT”; def px$i = 新 E(用户) if (!px$i.hasErrors()) { println "${px$i.name} / ${px$i.empr.to} 确定" }
EOT
$i++;
}
产生错误:
如果 borrar.pl 第 3 行没有包或对象引用,则无法调用方法“px”。
如何“转义” if ?
谢谢。
$i=1;
while($i<3) {
print << "EOT";
def px$i = new E(user)
if (!px$i.hasErrors()) {
println "${px$i.name} / ${px$i.empr.to} OK"
}
EOT
$i++;
}
produces the error:
Can't call method "px" without a package or object reference at borrar.pl line 3.
How can I "escape" the if ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
很难说这段代码应该完成什么任务,但也许您希望 println 语句中的外部美元符号保留在最终输出中?
经过这一更改,我看到的无错误输出是:
It's kind of hard to tell what this code is supposed to accomplish, but maybe you want the outer dollar signs in the println statement to be preserved in the final output?
With that change, the error-free output I see is:
命令行选项
-MO=Deparse
显示 Perl 在简化代码后如何解释代码(例如,将 heredocs 转换为 qq{} 块)。例如相关部分是:
Perl 已将
${px$i.name}
转换为${$i->px 。 '名字'}
!在 Perl 中,
${...}
表示评估块内的任何内容,并将其视为 符号引用(即变量名)或标量引用,然后取消引用它以将其恢复为标量。因此,Perl 尝试执行这些块内的任何内容,将其内容视为 Perl 代码。这是因为您的定界文档"EOT"
就像一个双引号字符串,并插入美元符号。解决方案是:转义美元符号 (
$
->\$
) 或使用单引号和连接而不是这里文档。The command line option
-MO=Deparse
shows you how Perl has interpreted your code after simplifying it (e.g. converting heredocs to qq{} blocks). e.g.The relevant part is:
Perl has converted
${px$i.name}
to${$i->px . 'name'}
!In perl,
${...}
means to evaluate whatever is inside the block, and treat it as a symbolic reference (i.e. a variable name) or a scalar reference, then dereference it to turn it back into a scalar. So Perl tries to execute whatever is inside those blocks, treating their contents as Perl code. This is because your heredoc,"EOT"
is like a double-quoted string, and interpolates dollar signs.Solution is: escape your dollar signs (
$
->\$
) or use single quotes and concatenation rather than heredocs.这应该可以解决问题。
This should fix the problem.
正如您所看到的,字符串的
$px
部分正在被评估。您只需要转义它:阅读有关字符串转义的更多信息 perldoc perlop 在“解析引用结构的血淋淋的细节”下。
As you have seen, the
$px
part of the string is getting evaluated. You simply need to escape it:Read more about string escaping at perldoc perlop under "Gory details of parsing quoted constructs".