Lesson 6 | Increment and decrement operators |
Objective | Write a program that uses the increment operator. |
Increment and Decrement Operators
Perl borrowed the increment and decrement operators from the C language, and added an enhancement in the process.
Numeric Context
The increment operator (++
) increments a numeric scalar variable, either before or after the variable is evaluated.
In order to increment the variable before it is evaluated, place the increment operator before the variable (e.g., ++$i
). To increment after the variable is evaluated, place the operator after the variable (for example, $i++
). For example, post-increment:
$i = 3;
# prints 3, then increments
print $i++;
And pre-increment:
$i = 3;
# increments, then prints 4
print ++$i;
The decrement operator has the same properties, post-decrement:
$i = 3;
# prints 3, then decrements
print $i--;
And pre-decrement:
$i = 3;
# decrements, then prints 2
print --$i;
String context
The increment operator works on string data as well (although the decrement operator does not).
In a string context, the increment operator increments string data as if they were numbers:
$s = "Ab";
$s++; # now it's "Ac"
$s = "A3";
$s++; # now it's "A4"
$s = "Baz";
$s++; # now it's "Bba"
Increment Operator - Exercise
Perl Complete Reference