# Thread: Help with operator precedence

1. Registered User
Join Date
Mar 2012
Posts
34

## Help with operator precedence

Hi
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

Code:
```\$value1 = 8;
\$value2 = 2;
\$value3 = \$value1-- % \$value2 * ++\$value2;
print (\$value3);

output: 0```
I also tried to see how it calculated by enclosing the expression in double quotes which returned the following -

Code:
```print "\$myvar1-- % \$myvar2 * ++\$myvar2";

output:  8-- % 2 * ++282```

2. 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:
Code:
```perl -MO=Deparse,-p precedence.pl
(\$value1 = 8);
(\$value2 = 2);
(\$value3 = (((\$value1--) % \$value2) * (++\$value2)));
print(\$value3);```
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)

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

3. 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.

4. Registered User
Join Date
Mar 2012
Posts
34
Hi
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