|
|
One of the key strengths of hashes in Perl is the ease with which you can create multi-dimensional hashes and then sort and traverse the stored values. Listing C.6 demonstrates how to create a two-dimensional Perl hash that associates an integer-valued scalar with a set of people who are identified by their first name and last name.
Listing C.6 multiHash1.pl
my($firstName) = ""; my($lastName) = ""; my($lastNameHash) = ""; my($employeeId) = ""; my(%Employees); my(%AllLastNames); $Employees{"Jones"}{"Tom"} = 1000; $Employees{"Smith"}{"Ann"} = 2000; $Employees{"Smith"}{"Bill"} = 3000; while(($lastName, $lastNameHash) = each(%Employees)) { $AllLastNames{$lastName} = $lastName; } for $lastName (sort (keys %AllLastNames)) { $lastNameHash = $Employees{$lastName}; while(($firstName, $employeeId) = each(%{$lastNameHash})) { print "$firstName $lastName has Id = $employeeId\n"; } }
You can launch the Perl script multiHash1.pl in Listing C.6 from the command line as follows,
perl -w multiHash1.pl
and the output is as follows:
Tom Jones has Id = 1000 Bill Smith has Id = 3000 Ann Smith has Id = 2000
|
|