Oops, that was wrong. Let's try again:
my $i = 0;
print ++$i + 1; # 1
print $i++ + 1; # 2
print $i + $i++; # 3
print ++$i + ++$i; # 4
print ++$i + $i++ + 1; # 5
Well, the first one is simple, 2.
The second one, also simple, 2 again.
The third one is where things get funky. $i++ changes the value of $i, and ++ is evaluated before +, so it could be written as:
my $old = $i++; print $i + $old;
Thus, "5" is printed.
Number 4 is fun too, because both the increments return not the new value of $i, but $i itself. Thus, it is the equivelant of:
++$i; ++$i; print $i + $i;
And thus, 10.
Number 5 will evaluate the first ++, incrementing and then returning $i (not that this is
different from the
value of $i), which means this is equivelant:
++$i; print $i + $i++ + 1;
Now, the post increment happens before the rest of it, but returns the old value, so we can write it like this:
++$i; my $old = $i++; print $i + $old + 1;
Resulting in 14.
Thus, the answer should be:
2
2
5
10
14
Two important things to note here: 1) the "post" and "pre" parts of "post-increment/pre-increment" means post- or pre-evaluation, not post- and pre-statement. 2) ++$i
does not return the new value of $i, but returns $i itself.
This is somewhat odd behaviour - generally you would expect that ++$i returns the new value of $i.
Jason Rhinelander
Gossamer Threads jason@gossamer-threads.com