Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Help me to understand increment / decrement operator behavior in perl

by andal (Hermit)
on Mar 04, 2015 at 08:24 UTC ( #1118724=note: print w/replies, xml ) Need Help??

in reply to Help me to understand increment / decrement operator behavior in perl

These increments/decrements cause quite a confusion :)

Actually one should remember, that postfix operation changes variable after the value is taken. It is not specified when exactly this "after" happens. One can be sure only, that when the value is taken next time, then it shall be changed value. Now, if you are referencing the same variable within single expression, then everything depends on time of access relative to postfix operation. If it is accessed before, then result shall be value before change. If it is accessed after, then it shall be changed value.

The problem is, most of the time it is not defined when the operation shall access variables. It is left up to the language implementation. So, perl operation $a == $a-- is not required to access content of the left operand before right one, or vice versa. Actually, I believe in this case opcode for $a simply marks address of the variable where value is stored, while opcode for $a-- first creates temporary variable referencing old content and then decrements content of the variable. So, the opcode for ==, which is executed after decrement, gets values from $a (which is already decremented) and then from temporary variable created by post-decrement. Of course the values are different.

So, general rule is: don't use variable with increments/decrements multiple times within single expression. You are only running into trouble, since in different implementations such expression may run differently. In this particular case, future implementations of perl could obtain values instead of marking address and then behavior would change.

  • Comment on Re: Help me to understand increment / decrement operator behavior in perl

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2022-11-30 21:00 GMT
Find Nodes?
    Voting Booth?