我在使用Perl脚本时遇到了一些奇怪的事情.这是关于使用一个点给出不同的结果.
perlop
什么都没有,或者我只是吹过它.我在看运算符优先级和关联性
print "I'd expect to see 11x twice, but I only see it once.\n";
print (1 . 1) . "3";
print "\n";
print "" . (1 . 1) . "3\n";
print "Pluses: I expect to see 14 in both cases, and not 113, because plus works on numbers.\n";
print (1 . 1) + "3";
print "\n";
print "" + (1 . 1) + "3\n";
Run Code Online (Sandbox Code Playgroud)
一开始就引用引号是一个可以接受的解决方法,以获得我想要的东西,但是这里发生的事情是我缺少的操作顺序?有什么规则可以学习?
Mar*_*eed 14
当您将第一个参数print
放在括号中时,Perl将其视为函数调用语法.
所以这:
print (1 . 1) . "3";
Run Code Online (Sandbox Code Playgroud)
被解析为:
print(1 . 1) . "3";
Run Code Online (Sandbox Code Playgroud)
或者,等效地:
(print 1 . 1) . "3";
Run Code Online (Sandbox Code Playgroud)
因此,Perl打印"11",然后获取该print
调用的返回值(1
如果它成功),连接3
它,并且 - 因为整个表达式在void上下文中 - 对结果完全没有任何作用13
.
如果您在启用警告的情况下运行代码(通过-w
命令行或use warnings;
编译指示),您将收到这些警告以识别您的错误:
$ perl -w foo.pl
print (...) interpreted as function at foo.pl line 2.
print (...) interpreted as function at foo.pl line 6.
Useless use of concatenation (.) or string in void context at foo.pl line 2.
Useless use of addition (+) in void context at foo.pl line 6.
Run Code Online (Sandbox Code Playgroud)
正如Borodin在下面的评论中指出的那样,你不应该依赖-w
(或代码中的等价物$^W
); 生产代码应该始终使用warnings
pragma,最好是使用use warnings qw(all);
.虽然在这个特定的实例中无关紧要use strict;
,但您也应该,尽管通过use
版本;
为Perl版本的5.11或更高版本请求现代功能也会自动启用strict
.
归档时间: |
|
查看次数: |
186 次 |
最近记录: |