in reply to Pre vs Post Incrementing variables

I think that if you read on, on the description of the auto-increment operators, or check perlop, you'll notice the following warning:

Note that just as in C, Perl doesn't define when the variable is incremented or decremented. 
You just know it will be done sometime before or after the value is returned. 
This also means that modifying a variable twice in the same statement will lead to undefined behaviour. 
Avoid statements like:
1. $i = $i ++; 2. print ++ $i + $i ++;
Perl will not guarantee what the result of the above statements is.

"Principle of Least Astonishment: Any language that doesn’t occasionally surprise the novice will pay for it by continually surprising the expert..

Replies are listed 'Best First'.
Re^2: Pre vs Post Incrementing variables
by JavaFan (Canon) on Sep 12, 2010 at 16:32 UTC
    The main reason it's declared as "undefined" is that the current implementation surprises many people, and can only be justified by exposing the implementation. Out of the two evils "having undefined behaviour" and "exposing the implementation to the language", I think the first one is the lesser.

    If you really need to increment $i twice, just write it in more than one statement:

    print $i + 1, $i + 1; $i += 2;
    print do {$i += 1}, do {$i += 1};
A reply falls below the community's threshold of quality. You may see it by logging in.