Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Pre vs Post Incrementing variables

by Erez (Priest)
on Sep 12, 2010 at 08:14 UTC ( [id://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..

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;
    Or:
    print do {$i += 1}, do {$i += 1};
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-23 13:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found