Hashes of Lists
#!/usr/bin/perl
#################### Perl "Records" As Hashes of Lists ###################
%bowling = ("Perry,John" => [124,145,101,98],
"Smith,Joe" => [187,190,209,176,195,203],
"Wonka,Willie" => [202,165,278]);
print "$bowling{'Perry,John'}->[2]\n";
print "$bowling{'Wonka,Willie'}[0]\n\n";
undef(%bowling);
################# Reading the Same Records from a File ##############
# The comments below show the format of file "data".
# Perry,John 124 145 101 98
# Smith,Joe 187 190 209 176 195 203
# Wonka,Willie 202 165 278
open(F,"data") or die "Cannot read data file.\n";
while(<F>)
{
($name, @scores) = split;
$bowling{$name} = [@scores]; # $bowling{$name} = \@scores is WRONG!!!!
}
print "$bowling{'Perry,John'}->[2]\n";
print "$bowling{'Wonka,Willie'}[0]\n\n";
################### Output Records in Key Order #####################
foreach $name (sort keys %bowling)
{
print "@{$bowling{$name}}\n"; # Each key's value is a list
# ref., hence the @ dereference!
}
print "\n";
######## Sending a Hash of Lists to a Function Via References ###########
%bowling = ("Perry,John" => [124,145,101,98],
"Smith,Joe" => [187,190,209,176,195,203],
"Wonka,Willie"=> [202,165,278]);
change_hash(\%bowling);
foreach $name (keys %bowling)
{
print "@{$bowling{$name}}\n"; ####### Output #4 in id order
}
print "\n\n";
sub change_hash
{
my ($href) = shift;
foreach $name (keys %$href)
{
$href->{$name}->[1] = 50; # $href->{$name}[1] works! Adjacent
} # indexes can omit intervening arrow.
}
################################## Program Output ###########################
101
202
101
202
124 145 101 98
187 190 209 176 195 203
202 165 278
202 50 278
124 50 101 98
187 50 209 176 195 203