Unary Arithmetic Operators
As if $variable += 1 weren’t short enough, Perl borrows from C an even shorter
way to increment a variable. The autoincrement (and autodecrement)
operators simply add (or subtract) one from the value of the variable.
They can be placed on either side of the variable, depending on when you
want them to be evaluated; see Table 1-3.
Table 1-3. Increment operators
| Example | Name | Result |
|---|---|---|
++$a,
$a++ | Autoincrement | Add 1 to $a |
––$a,
$a–– | Autodecrement | Subtract 1 from $a |
If you place one of these “auto” operators before the variable, it is known as a preincremented (predecremented) variable. Its value will be changed before it is referenced. If it is placed after the variable, it is known as a postincremented (postdecremented) variable, and its value is changed after it is used. For example:
$a = 5; # $a is assigned 5 $b = ++$a; # $b is assigned the incremented value of $a, 6 $c = $a––; # $c is assigned 6, then $a is decremented to 5
Line 19 of our Average Example increments the number of scores by
one so that we’ll know how many scores we’re averaging. It uses a
postincrement operator ($scores++),
but in this case it doesn’t matter since the expression is in void
context, which is just a funny way of saying that the expression is
being evaluated only for the side effect of incrementing the variable.
The value returned is being thrown away.[26]
[26] The optimizer will notice this and optimize the postincrement into a preincrement, because that’s a bit faster to execute. (You didn’t ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access