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);foreachmy$item(@required){unless($skipper{$item}){# not found in list?"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 ...