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 += $_] ?
Hm, no, I don't think that explains it.
Operator precedence requires, of course, that the += operator is evaluated before the , operator is evaluated, but it does not explain why the += operator is evaluated before the first argument to the , operator is evaluated.
And indeed, with other operators (i.e. other than ++ or += and friends), this does not happen. For example, . also has higher precedence than , but it does not cause the second decorate() call to happen before the first in the following example:
use feature qw(say state); sub decorate { state $counter = 0; return ++$counter . ':' . shift } my @a = ( decorate("foo"), decorate("bar") . "!" ); say "@a"; # prints "1:foo 2:bar!" and not "2:foo 1:bar!"
If I correctly understand the perlop paragraph quoted by Eily below, it appears that auto-increment operators only participate in the normal evaluation order as far as their return value is concerned, but their side-effect (modifying the variable) happens at an undefined time.
I really wonder why that is the case, though. Just as a function's side-effects happen when the function call is evaluated (from the point of view of the larger expression), I would have expected the side-effect of += to happen when it's the operator's turn to be evaluated in the evaluation order of the larger expression.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Why does the first $c evaluate to the incremented value in [$c, $c += $_] ?
by Eily (Monsignor) on Mar 04, 2014 at 23:29 UTC | |
by smls (Friar) on Mar 05, 2014 at 00:34 UTC |