Perl a开头的点;“打印”;陈述

Perl a开头的点;“打印”;陈述,perl,operations,Perl,Operations,我在使用Perl脚本时遇到了一些奇怪的情况。这是关于使用一个点给出不同的结果 没有发现任何东西,或者我只是吹过去了。我在看 print“我希望看到11x两次,但只看到一次。\n”; 印刷品(1.1)。"3"; 打印“\n”; 打印“”。(1 . 1) . “3\n”; print“plus:我希望两种情况下都是14,而不是113,因为plus适用于数字。\n”; 印刷品(1.1)+“3”; 打印“\n”; 打印“”+(1.1)+“3\n”; 在一开始就加引号是一个可以接受的解决办法,可以得到我

我在使用Perl脚本时遇到了一些奇怪的情况。这是关于使用一个点给出不同的结果

没有发现任何东西,或者我只是吹过去了。我在看

print“我希望看到11x两次,但只看到一次。\n”;
印刷品(1.1)。"3";
打印“\n”;
打印“”。(1 . 1) . “3\n”;
print“plus:我希望两种情况下都是14,而不是113,因为plus适用于数字。\n”;
印刷品(1.1)+“3”;
打印“\n”;
打印“”+(1.1)+“3\n”;

在一开始就加引号是一个可以接受的解决办法,可以得到我想要的东西,但是我所缺少的操作顺序在这里发生了什么?有哪些规则需要学习?

当您将第一个参数置于括号中的
print
时,Perl将其视为函数调用语法

因此:

print (1 . 1) . "3";
解析为:

print(1 . 1)  . "3";
或者,相当于:

(print 1 . 1) . "3";
因此,Perl打印“11”,然后获取
print
调用的返回值(如果成功,则返回值为
1
),将
3
连接到它,并且-由于整个表达式处于无效上下文中-对结果
13
完全不做任何处理

如果在启用警告的情况下运行代码(通过命令行上的
-w
use warnings;
pragma),您将收到这些用于识别错误的警告:

$ 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.
正如博罗丁在下面的评论中指出的那样,您不应该依赖于
-w
(或代码内等价物
$^w
);生产代码应始终使用
警告
杂注,最好使用
使用警告qw(全部)。虽然在这个特殊的例子中这并不重要,但是您也应该
使用strict,尽管通过
使用
版本
请求现代功能也会自动启用
strict

如果命名运算符(或子调用)后面跟有paren,则这些paren会分隔操作数(或参数)

请注意,如果您一直使用(
use strict;
和)
use warnings qw(all),Perl会提醒您出现问题如您所愿

print (...) interpreted as function at a.pl line 2.
print (...) interpreted as function at a.pl line 6.
Useless use of concatenation (.) or string in void context at a.pl line 2.
Useless use of addition (+) in void context at a.pl line 6.
I'd expect to see 11x twice, but I only see it once.
11
113
Pluses: I expect to see 14 in both cases, and not 113, because plus works on numbers.
11
Argument "" isn't numeric in addition (+) at a.pl line 8.
14

perldoc perlfunc
:“下面列表中的任何函数都可以在其参数周围使用圆括号或不使用圆括号。(语法描述省略圆括号)。如果使用圆括号,简单但偶尔令人惊讶的规则是:它看起来像一个函数,因此它是一个函数,优先级无关紧要。”谢谢我使用严格的;使用警告;对于更大的项目,但只有十行或更少的行,我只是勉强通过。因此,我的这个问题是为所有新的perl文件(无论大小)提供一个小模板的转折点。这包括标题注释和使用严格;使用警告来捕获此类问题。
print (...) interpreted as function at a.pl line 2.
print (...) interpreted as function at a.pl line 6.
Useless use of concatenation (.) or string in void context at a.pl line 2.
Useless use of addition (+) in void context at a.pl line 6.
I'd expect to see 11x twice, but I only see it once.
11
113
Pluses: I expect to see 14 in both cases, and not 113, because plus works on numbers.
11
Argument "" isn't numeric in addition (+) at a.pl line 8.
14