A Hash of Hashes
February 7, 2000
A student is not unlike a new car, although less reliable
and probably washed less frequently. Still, a student
possesses a set of characteristics, such as their class year,
major of study, and grade point average. In fact, we can wrap
all of these properties into a hash. We can then say that
this hash is in fact a value whose key is the student's
name. Yes, a hash of a hash.
Consider the plight of Nick Plato, estranged descendent of
the famous Athenian Plato line. Nick's student hash might
look something like:
%students=("Nick Plato"=>{"year"=>"2",
"GPA"=>"2.5",
"major"=>"Phys. Ed.",
"email"=>"nplato\@school.edu"});
The students hash contains one key,
"Nick Plato", whose value
is a hash. We can reference, for instance, Nick's GPA as
follows:
$students{"Nick Plato"}{"GPA"}
You can't have a party of one, so let's throw a couple of
more student hashes into the mix.
$students{"Mary Pitts"}=({"year"=>"4",
"GPA"=>"4","major"=>"Economics",
"email"=>"mpitts\@school.edu"});
$students{"Sally Cummings"}=({"year"=>"1",
"GPA"=>"3.3","major"=>"Undecided",
"email"=>"scummings\@school.edu"});
As we've seen before, you can add keys to a hash through
simple assignment. In this case, we're again addings keys
whose values are themselves hashes. Now suppose that we wish
to output all records for each student, sorted by descending
GPA, with the records internally sorted by alphabet.
#Double-Sort students by GPA and keys
print "\nAll students sorted by GPA:\n";
foreach $student
(reverse sort {$students{$a}{GPA}<=>$students{$b}{GPA} }
keys (%students))
{print "$student\n";
foreach $recorditem (sort keys %{$students{$student} })
{print "\t$recorditem: $students{$student}{$recorditem}\n"}
}
The list of all students is represented by the function
keys (%students). We want to sort this list by
associated GPA, however. Thus a custom reverse sort is
executed where we compare the "GPA" key values
within the student hash ($students{$a} and
$students{$b}). As we iterate over each student hash,
then, we retrieve the list of records within the student
hash (keys %{$students{$student} }) and sort these by
the default alphabetic scheme. Each record is then output,
in the syntax we saw when accessing Nick Plato's GPA.
A Hash of Lists
The Perl You Need to Know
Reprieve
|