I'm having some trouble wrapping my head around perl's order of operations. I have the following:
>> my $n = 2;
>> my @arr = (1,2,3,4);
>> print $n/scalar @arr * 100;
0.005
But adding parens:
>> my $n = 2;
>> my @arr = (1,2,3,4);
>> print $n/(scalar @arr) * 100;
50
Looking at the order of operations, it seems as though the first thing that should happen are list operations. In this case, the first one encountered would be scalar @arr
, which should return 4. The resulting expression should be print $n/4 * 100
, which would follow a standard order of operations and produce 50
.
But instead, I assume what is happening is it is performing @arr * 100
first, which produces the scalar value 400
, then executed scalar 400
, which produces 400
, then executes $n/400
, giving 0.005
.
If the latter is what is happening, then my question is where does scalar
fall in the order of operations. If something else is going on, then my question is, well, what?
You can see how Perl parses the code by running it through B::Deparse with -p
:
perl -MO=Deparse,-p script.pl
I tried 3 different ways:
print $n/scalar @arr * 100;
print $n/(scalar @arr) * 100;
print $n/@arr * 100;
This was the output:
print(($n / scalar((@arr * 100))));
print((($n / scalar(@arr)) * 100));
print((($n / @arr) * 100));
*
is higher than the "named unary operators" (where scalar belongs, check the link) in the precedence table in perlop.