A Hash of Lists
February 7, 2000
The question is, what can be more confusing than a list of
hashes, and also, will we ever stop subtly but
unintentionally promoting Toyotas? The answers: a hash of
lists, and yes, right now. To best illustrate a hash of
lists, let's move away from cars and think of school.
More specifically, student rosters. Instead of a used car
salesman, you've been promoted to a professorship, and
you head three class sessions per day (the rigors of academic
life): Psych 101A, Psych 101B, and Psych 103. Each class
has a student roster.
What we have, then, is a classic hash -- the course code is
the key ("Psych 101A") and the student roster is
the value. The hitch is that the student roster is, itself,
a list.
%roster=("Psych 101A"=>["Sue Draper",
"Mike Jones",
"Iiago Stein"]);
Here we setup a hash, roster, where the value is a
list, and therefore enclosed in square brackets. Adding
class-roster pairs to the hash is easy, since we can simply
assign new keys to a hash on-the-fly.
$roster{"Psych 101B"}=(["J.P. Hertz",
"Mark Simon","Freedy Bender"]);
$roster{"Psych 103"}=(["Iiago Stein",
"Freedy Bender","Jill Portman"]);
You'll notice that a couple of students appear in both Psych
101 and Psych 103 rosters. They're overachievers. Now, let's
suppose you simply want to output the answer to "Who
are the students in my Psych 103 class?"
foreach $student ( @{$roster{"Psych
103"} })
{ print "$student " }
Yields:
Iiago Stein Freedy Bender Jill Portman
Actually, maybe it would be better to sort the students by
last name. Recall our by_lastname subroutine for
the sort function.
foreach $student
( sort by_lastname @{$roster{"Psych 103"} })
{ print "$student " }
sub by_lastname {
($a_lastname)=$a=~/(\w+)$/;
($b_lastname)=$b=~/(\w+)$/;
return $a_lastname cmp $b_lastname
}
Yields:
Freedy Bender Jill Portman Iiago Stein
One day, the dreaded new student shows up for Psych 101B
session. But with your handy hash of lists, you don't need
to start the rosters from scratch ... simply push
the new student onto the list that is the value of the
"Psych 101B" key.
push(@{$roster{"Psych 101B"} },"N.K.
Block");
Still, something seems to be missing from this picture.
Our student rosters are handy, but a list of student names
is of limited use ... there's more to a student than simply
their name. In fact, one might say that a student is themself
a type of hash ...
A List of Hashes
The Perl You Need to Know
A Hash of Hashes
|