Autoincrement and Autodecrement
The ++ and –– operators work as in C. That is, when placed before a variable, they
increment or decrement the variable before returning the value; when
placed after, they increment or decrement the variable after returning the
value. For example, $a++ increments the
value of scalar variable $a, returning
the value it had before the increment. Similarly,
––$b{(/(\w+)/)[0]} decrements the
element of the hash %b indexed by the
first “word” in the default search variable ($_) and returns the value
after the decrement.[60] 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 behavior. Avoid statements like:
$i = $i++; print ++$i + $i++;
Perl will not guarantee the results of such code.
The autoincrement operator has a little extra built-in magic. If you
increment a variable that is numeric, or that has ever been used in a
numeric context, you get a normal increment. If, however, the variable has
been used only in string contexts since it was set, has a value that is
not the null string, and matches the pattern /^[a–zA–Z]*[0–9]*\z/, the increment is done as a
string, preserving each character within its range, with carry:
my $foo; $foo = "99"; print ++$foo; # prints "100" $foo = "a9"; print ++$foo; # prints "b0" $foo = "Az"; print ++$foo; # prints "Ba" ...
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