Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Pre vs Post Incrementing variables

by Erez (Priest)
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..

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};
Re^2: Pre vs Post Incrementing variables
by Anonymous Monk on Sep 24, 2016 at 10:37 UTC
    I am expecting like this for a file.

    input

    Hi hello world Hi hello world .
    output
    1.1 Hi 1.2 hello 1.3 world 2.1 Hi 2.2 hello 2.3 world 2.4 .
    again new sentence will come

      Hello, I don't see exactly how this is related to the overall thread, so you may benefit from starting a new one.

      Either way, the best way of getting an answer regarding your problem is giving more context, mainly, the part of the program that is giving you the unwanted output, and what is the wanted output, since it's entirely unclear (to me) from the example you give here.

      Hope this helps

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

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 avoiding work at the Monastery: (4)
As of 2016-09-28 04:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (518 votes). Check out past polls.