http://www.perlmonks.org?node_id=1077073


in reply to Re: Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?
in thread Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?

Well, quote-like operators have higher precedence than +=, so your example can still be explained by the "sub-expressions with higher-precedence operators are evaluated first" rule.

And in the last example, both shift's have the same precedence, so it goes from left to right "as a last resort".

Although, come to think of it, terms are technically supposed to have highest precedence. Yet for some reason, term subexpressions are evaluated last (see my demonstration using tied scalars above).

All things taken together, it seems the rules for expression evaluation order in Perl can be described like so:

  1. An expression is viewed as a tree whose branch nodes are operators and whose leaf nodes are terms, constructed in accordance with any grouping parenthesis and the precedence of the involved operators.
  2. It follows that sub-expressions which appear as "sibling nodes" in that tree are independent of each other, and if they are all side-effect-free, the order of their evaluation relative to each other is irrelevant. However, if they do have side-effects, it becomes significant. That's where rule 3 comes in:
  3. Sibling sub-expressions are evaluated in decreasing order of operator precedence (if they are themselves operators), or last (if they are terms). Sibling of the same precedence group (and only those!) are evaluated left-to-right.

Which still does not answer the question of "Why on earth would it be defined like that?", though. I really don't think it contributes to DWIM. I think it would be more intuitive if the third rule were simply:

  1. Sibling sub-expressions are evaluated from left to right.

Maybe it's a performance optimization though, because it allows the compiler to only fetch the values of term once it actually needs to evaluate their parent expression?