XP is just a number | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
<Update> After writing this, I realize that it makes no difference that ++$i returns an alias. But I'm too lazy to rewrite the whole thing. The main point is the order in which you evaluate the arguments to the addition operation in those big expressions.</Update>
Update2: changed my example so that aliases *did* make a difference. Thanks ysth++.
Statements like yours (with multiple assignments to $i in a single statement) are confusing/unpredictable because there are aliases involved. Preincrement ++$i returns an alias to $i, while postincrement $i++ returns just a plain old value. You can see that this is the case: Now that you know aliases are involved, it's a simple matter of just following the execution.. No magic involved. So let's look an example: First, recall that addition is left-associative. Also, check that when evaluating an addition, perl evaluates the left argument before the right argument. At least, that's how it happens in my perl. If there is anything "undefined" about your test cases, it is this part, not the fact that you are using increment operators. So here's how perl evaluates this statement:
Now hopefully you agree with what everyone has been saying, that assigning to a variable multiple times while using its value in the same statement is really not worth it. But I wouldn't say that it's black magic, once you understand about aliasing. It's up to you to decide it perl will ever do anything other than left-to-right evaluation of arguments to the addition operator. I guess if perl wants to reserve the right to do something else, you'll have to respect that. blokhead In reply to Re: Auto Increment "magic" Inquiry
by blokhead
|
|