Skip to Content
Intermediate Perl, 2nd Edition
book

Intermediate Perl, 2nd Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
July 2012
Intermediate to advanced
396 pages
9h 16m
English
O'Reilly Media, Inc.
Content preview from Intermediate Perl, 2nd Edition

Chapter 4. Introduction to References

References are the basis for complex data structures, object-oriented programming, and fancy subroutine handling. They’re the magic that was added between Perl versions 4 and 5 to make it all possible.

A Perl scalar variable holds a single value. An array holds an ordered list of scalars. A hash holds an unordered collection of scalars as values, keyed by strings. Although a scalar can be an arbitrary string, which lets us encode complex data in an array or hash, none of the three data types are well suited to complex data interrelationships. This is a job for the reference. We look at the importance of references by starting with an example.

Doing the Same Task on Many Arrays

Before the Minnow can leave on an excursion (for example, a three-hour tour), we should check every passenger and crew member to ensure they have all the required trip items in their possession. For maritime safety, every person aboard the Minnow needs to have a life preserver, some sunscreen, a water bottle, and a rain jacket. We can write a bit of code to check for the Skipper’s supplies:

my @required = qw(preserver sunscreen water_bottle jacket);
my %skipper  = map { $_, 1 }
  qw(blue_shirt hat jacket preserver sunscreen);

foreach my $item (@required) {
  unless ( $skipper{$item} ) { # not found in list?
    print "Skipper is missing $item.\n";
  }
}

Notice that we created a hash from the list of the Skipper’s items. That’s a common and useful operation. Since we want to check if a ...

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

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl & LWP

Perl & LWP

Sean M. Burke
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan

Publisher Resources

ISBN: 9781449343781Errata Page