Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Pre vs Post Incrementing variables

by Erez (Curate)
on Sep 12, 2010 at 08:14 UTC ( #859814=note: print w/ replies, xml ) Need Help??


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..


Comment on Re: Pre vs Post Incrementing variables
Download Code
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;
    Or:
    print do {$i += 1}, do {$i += 1};

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://859814]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (16)
As of 2014-10-30 13:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (208 votes), past polls