Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
You’ll often want a scalar variable to count up or down by one. Since these are frequent constructs, there are shortcuts for them, like nearly everything else we do frequently.
The autoincrement operator (++) adds one to a scalar variable, like the
same operator in C and similar languages:
my $bedrock = 42; $bedrock++; # add one to $bedrock; it's now 43
Just like other ways of adding one to a variable, the scalar will be created if necessary:
my @people = qw{ fred barney fred wilma dino barney fred pebbles };
my %count; # new empty hash
$count{$_}++ foreach @people; # creates new keys and values as needed
The first time through that foreach loop, $count{$_} is incremented. That’s $count{"fred"}, which thus goes from undef (since it didn’t previously exist in the
hash) up to 1. The next time through
the loop, $count{"barney"} becomes
1; after that, $count{"fred"} becomes 2. Each time through the loop, you increment
one element in %count, and possibly
create it as well. After that loop finishes, $count{"fred"} is 3. This provides a quick and easy way to see
which items are in a list and how many times each one appears.