perl:数组操作的优先级
perl: precedence of array operations
我在理解 perl 的操作顺序时遇到了一些麻烦。我有以下内容:
>> my $n = 2;
>> my @arr = (1,2,3,4);
>> print $n/scalar @arr * 100;
0.005
但添加括号:
>> my $n = 2;
>> my @arr = (1,2,3,4);
>> print $n/(scalar @arr) * 100;
50
查看 order of operations,似乎首先应该发生的事情是列表操作。在这种情况下,遇到的第一个将是 scalar @arr
,它应该是 return 4. 结果表达式应该是 print $n/4 * 100
,它将遵循标准的操作顺序并产生 50
.
但是,我假设正在发生的事情是它首先执行 @arr * 100
,生成标量值 400
,然后执行 scalar 400
,生成 400
, 然后执行 $n/400
, 给出 0.005
.
如果是后者,那么我的问题是 scalar
在操作顺序中的位置。如果发生其他事情,那么我的问题是,嗯,什么?
来自 perlop 文档
In the absence of parentheses, the precedence of list operators such
as print, sort, or chmod is either very high or very low depending on
whether you are looking at the left side or the right side of the
operator. For example, in
@ary = (1, 3, sort 4, 2);
print @ary; # prints 1324
the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all the arguments that follow them, and then act like a simple TERM with regard to the preceding expression.
并且 *
运算符的优先级 7.
高于命名一元运算符 10.
因此在 scalar @arr * 100
*
中具有更高的优先级。
您可以看到 Perl 如何通过 运行 通过 B::Deparse 和 -p
:
解析代码
perl -MO=Deparse,-p script.pl
我尝试了 3 种不同的方式:
print $n/scalar @arr * 100;
print $n/(scalar @arr) * 100;
print $n/@arr * 100;
这是输出:
print(($n / scalar((@arr * 100))));
print((($n / scalar(@arr)) * 100));
print((($n / @arr) * 100));
*
高于 "named unary operators"(其中 scalar belongs, check the link) in the precedence table in perlop.
我在理解 perl 的操作顺序时遇到了一些麻烦。我有以下内容:
>> my $n = 2;
>> my @arr = (1,2,3,4);
>> print $n/scalar @arr * 100;
0.005
但添加括号:
>> my $n = 2;
>> my @arr = (1,2,3,4);
>> print $n/(scalar @arr) * 100;
50
查看 order of operations,似乎首先应该发生的事情是列表操作。在这种情况下,遇到的第一个将是 scalar @arr
,它应该是 return 4. 结果表达式应该是 print $n/4 * 100
,它将遵循标准的操作顺序并产生 50
.
但是,我假设正在发生的事情是它首先执行 @arr * 100
,生成标量值 400
,然后执行 scalar 400
,生成 400
, 然后执行 $n/400
, 给出 0.005
.
如果是后者,那么我的问题是 scalar
在操作顺序中的位置。如果发生其他事情,那么我的问题是,嗯,什么?
来自 perlop 文档
In the absence of parentheses, the precedence of list operators such as print, sort, or chmod is either very high or very low depending on whether you are looking at the left side or the right side of the operator. For example, in
@ary = (1, 3, sort 4, 2); print @ary; # prints 1324
the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all the arguments that follow them, and then act like a simple TERM with regard to the preceding expression.
并且 *
运算符的优先级 7.
高于命名一元运算符 10.
因此在 scalar @arr * 100
*
中具有更高的优先级。
您可以看到 Perl 如何通过 运行 通过 B::Deparse 和 -p
:
perl -MO=Deparse,-p script.pl
我尝试了 3 种不同的方式:
print $n/scalar @arr * 100;
print $n/(scalar @arr) * 100;
print $n/@arr * 100;
这是输出:
print(($n / scalar((@arr * 100))));
print((($n / scalar(@arr)) * 100));
print((($n / @arr) * 100));
*
高于 "named unary operators"(其中 scalar belongs, check the link) in the precedence table in perlop.