使用子程序和乘法运算符的明显奇怪性

Lit*_*rat 4 perl

请你解释一下*显然*不一致的行为给我:

use strict;
sub a { 2 + 2 };
print 2 * a(); # this prints: 8
print a() * 2; # this prints: 8
print 2 * a;   # this prints: 8
print a * 2;   # this prints: 4
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答,非常有帮助 - 我学到了很多东西.

yst*_*sth 12

Deparse显示你正在将glob传递给最后一个:

$ perl -MO=Deparse,-p
use strict;
sub a { 2 + 2 };
print 2 * a(); # this prints: 8
print a() * 2; # this prints: 8
print 2 * a; # this prints: 8
print a * 2; # this prints: 4
__END__
sub a {
    use strict 'refs';
    4;
}
use strict 'refs';
print((2 * a()));
print((a() * 2));
print((2 * a()));
print(a(*2));
Run Code Online (Sandbox Code Playgroud)

在子程序调用中使用parens是一件好事......


Eri*_*rom 6

在最后一个示例中,表达式被解析为使用glob参数进行a(*2)调用a,该参数*2是包变量的短名称*main::2

如果要将a其解析为不带参数的函数,则需要将其声明为:

sub a () {2 + 2}
Run Code Online (Sandbox Code Playgroud)

然后perl将按预期解析语句.事实上,如果你这样写,perl将检测到它是一个常量函数,并将4在每个a被调用的地方内联.