in reply to pre v.s. post (increment/decrement)

Relevant snippet from perlop:

"++" and "--" work as in C. That is, if placed before a variable, they increment or decrement the variable before returning the value, and if placed after, increment or decrement the variable after returning the value.

The only difference is in what value is returned. Maybe the following code will demonstrate the difference more clearly:

$a = 1; print ++$a, ":", $a, "\n"; $a = 1; print $a++, ":", $a, "\n";

Update: yikes. 2 answers were posted in the time it took me to compose mine. I had a feeling this would happen with a question like this... :)

Replies are listed 'Best First'.
Re: pre v.s. post (increment/decrement)
by Abigail-II (Bishop) on Jul 11, 2003 at 00:01 UTC
    I fail to see the problem. Pre-increment means that the value will be incremented before the value is returned. Post-increment means the value will be incremented after it is returned. It's very important to realize that it is not defined exactly when the increment occurs. It will be done after execution of the current statement started, and will be done before the statement is finished, but that's all you get.

    So, for your first line, you could get "2:2", or "2:1" and for the second line, you could get "1:2" or "1:1". Or some other weird value for the second $a.

    As a rule, never use a variable you are pre- or post incrementing or decrementing a second time in the same statement. And most certainly, don't modify the variable a second time. The following is undefined:

    my $i = 0; $i = ++ $i;
    meaning that if perl decides to erase your hard disk, it's still well inside the boundaries of its specification.

    Abigail