http://qs321.pair.com?node_id=643679


in reply to Autoincrement operator precedence difference between C and Perl

I'm surprised everyone is attributing the weird results to the order in which Perl operators evaluate their arguments. Perl doesn't have a weird evaluation order. It does things left-to-right as you would expect. Even if it did, it wouldn't sufficiently describe the outputs above. The order in which arguments are evaluated is not specified as a feature, sure, but it's not like Perl is trying to be smart and do things in different orders each time. It reserves the right to do so, but as far as I know it does not. Also, I do not think it splits up the atomic operations $i++ or ++$i into smaller bits, as the C optimizer might be doing, but I don't know how to check for sure. My hunch is because the increment operator is "magic" while +=1 is not.

I can't speak to what happens in C. But the real weirdness in Perl comes from the fact that the pre-increment operator returns an alias to $i (post-increment returns a plain old value). So in some of these examples, Perl evaluates the first ++$i, which returns an alias. The second increment operator changes $i. Because the first value is an alias to $i, its value also gets changed in this step before the addition operator acts on it. That is why ++$i + ++$i returns a value that is 4 greater than $i+$i: both increment operations increase both operands.

Under this interpretation and left-to-right evaluation, you can fully describe the behavior of all of these expressions.

blokhead