http://qs321.pair.com?node_id=1118724


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