Help with operator precedence
I am having a bit of a problem working out operator precedence in the follow expression, the output of which is 0.
I realize ++$value2 is incremented immediately so both ++$value2s should now contain 3,
and $value1-- is not decremented immediately so contains 8, which should make the expression
8 % 3 * 3 which when run mysteriously returns 6, 8 / 3 has remainder 2, 2 * 3 = 6, I had a look at a perl operator
precedence chart, which said * is before % this would make the expression 8 % 9
I also tried to see how it calculated by enclosing the expression in double quotes which returned the following -
$value1 = 8;
$value2 = 2;
$value3 = $value1-- % $value2 * ++$value2;
print "$myvar1-- % $myvar2 * ++$myvar2";
output: 8-- % 2 * ++282
There's a neat module called B::Deparse, that can show you how exactly the perl interpreter understands your code. I saved the code in a file called precedence.pl and called the following line and getting the following output:
This means you get 8%2, which is 0 times whatever, so obviously 0; Only after the multiplication is carried out, the increment takes place, though the incremented value is used. So you have ((8%2)*3)
perl -MO=Deparse,-p precedence.pl
($value1 = 8);
($value2 = 2);
($value3 = ((($value1--) % $value2) * (++$value2)));
The quote approach can of course not work, because you only get the variables interpolated and not the operators.
Last edited by Sixtease; 01-24-2014 at 05:34 AM.
Reason: stupid emoticons
By the way, the difference between saying $foo++ vs ++$foo is not that ++$foo is somehow incremented sooner or "immediately". It merely means that the expression returns the original or the incremented value respectively.
Many thanks for replying!
As suggested I downloaded the module from cpan as it wasn't available in the Activeperl package manager.
I am sure it will be invaluable to me. Also the syntax used must be exact perl -MO=Deparse,-p precedence.pl
the first time I ran it I mistakenly included a space between the , - and got totally different output.
Best regards Maxwell
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)