You have to understand how expressions evaluate. The pre- and post-increment (and decrement) operators change the variables value, but the variable plus the operator constitute and expression who's value varies depending upon the placement of the ++. Essentially, the value of the expression $i++ is original value of $i and $i is incremented by 1. The value of the expression ++$i is new value of $i after $i is incremented by 1.
$i = ++$i + $i++;
In the above example, we evaluate the expression right to left. The expression, $i++, evaluates as zero, even though $i is now 1. The second expression, ++$i, evaluates as 2 (since $i is now 1) and 2+1 equals 3.
$i = $i++ + ++$i;
Pretty straightforward now. The rightmost ++$i evaluates as 1 and $i is set to one. The $i++ also evaluates to 1 (remember, with a post-increment operator doesn't change the return value of the expression, just the variable -- confused yet? :). So, 1 + 1 equals two.
Cheers,
Ovid
Update: Got the concept right, but I evaluated in reverse order. Whoops! Juerd is right.
Update2: Okay, I'm smoking crack. If things are evaluated left to right, then the following is true:
$ perl -e 'print 1-3+2' 0
Well, it turns out that this is true. If it were evaluated right to left, then the answer would negative four. What I think is going on (though I can't prove it offhand) is that built-in unary operators are evaluated right to left, and then the rest of the expression is evaluated based upon precedence rules, if any. Anyone want to shed light on this?
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to Re: $i=$i++
by Ovid
in thread $i=$i++
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |