Path: usenet.cis.ufl.edu!usenet.eel.ufl.edu!news.mathworks.com!news.kei.com!simtel!news.sprintlink.net!in1.uu.net!csnews!alumni.cs.colorado.edu!tchrist
From: Tom Christiansen <
[email protected]>
Newsgroups: comp.lang.perl.misc,comp.lang.perl.announce
Subject: PDSC Recipes for Hashes of Lists (part 2 of 5)
Followup-To: comp.lang.perl.misc
Date: 2 Oct 1995 01:51:59 GMT
Organization: Perl Consulting and Training
Lines: 81
Approved:
[email protected]
Message-ID: <
[email protected]>
References: <
[email protected]>
Reply-To:
[email protected] (Tom Christiansen)
NNTP-Posting-Host: alumni.cs.colorado.edu
Originator:
[email protected]
Xref: usenet.cis.ufl.edu comp.lang.perl.misc:7630 comp.lang.perl.announce:134
PDSC: The Perl Data Structures Cookbook
part 2 of 5: Hashes of Lists
by Tom Christiansen
<
[email protected]>
release 0.1 (untested, may have typos)
Sunday, 1 October 1995
Declaration of a HASH OF LISTS:
%HoL = (
"flintstones" => [ "fred", "barney" ],
"jetsons" => [ "george", "jane", "elroy" ],
"simpsons" => [ "homer", "marge", "bart" ],
);
Generation:
# reading from file
# flintstones: fred barney wilma dino
while ( <> ) {
next unless s/^(.*?):\s*//;
$HoL{$1} = [ split ];
}
# reading from file; more temps
# flintstones: fred barney wilma dino
while ( $line = <> ) {
($who, $rest) = split /:\s*/, $line, 2;
@fields = split ' ', $rest;
$HoL{$who} = [ @fields ];
}
# calling a function that returns a list
for $group ( "simpsons", "jetsons", "flintstones" ) {
$HoL{$group} = [ get_family($group) ];
}
# likewise, but using temps
for $group ( "simpsons", "jetsons", "flintstones" ) {
@members = get_family($group);
$HoL{$group} = [ @members ];
}
# append new members to an existing family
push @{ $HoL{"flintstones"} }, "wilma", "betty";
Access and Printing:
# one element
$HoL{flintstones}[0] = "Fred";
# another element
$HoL{simpsons}[1] =~ s/(\w)/\u$1/;
# print the whole thing
foreach $family ( keys %HoL ) {
print "$family: @{ $HoL{$family} }\n"
}
# print the whole thing with indices
foreach $family ( keys %HoL ) {
print "family: ";
foreach $i ( 0 .. $#{ $HoL{$family} ) {
print " $i = $HoL{$family}[$i]";
}
print "\n";
}
# print the whole thing sorted by number of members
foreach $family ( sort { @{$HoL{$b}} <=> @{$HoL{$b}} } keys %HoL ) {
print "$family: @{ $HoL{$family} }\n"
}
# print the whole thing sorted by number of members and name
foreach $family ( sort { @{$HoL{$b}} <=> @{$HoL{$a}} } keys %HoL ) {
print "$family: ", join(", ", sort @{ $HoL{$family}), "\n";
}