Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Autoincrement and Autodecrement

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, one element in %count is incremented, and possibly created as well. After that loop is done, $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.

Similarly, the autodecrement operator (--) subtracts one from a scalar variable:

$bedrock--;  # subtract one from $bedrock; it's 42 again

The Value of Autoincrement

You can fetch the value of a variable and change that value at the same time. Put the ++ operator in front of the variable name to increment the variable first and then fetch its value. ...

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.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page