Please browse through faq219-2884 and faq219-2889 first. Comments on this FAQ and the General FAQ's are very welcome.
I had a real mental block about hashes of hashes, arrays of hashes, arrays of arrays -- and all because they use references.
It turns out they're actually quite easy.
Here's a short script that demonstrates how to group related data together in a sensible structure.
[tt]
#
# how to use an hash of hashes
#
use strict;
use warnings;
my (%hash, $key);
my ($i, $fname, $lname, $mental_age);
# reads data from after __END__ in this file
while(<DATA>){
# get a line of data
next if /^\s+$/;
chomp;
my ($i, $fname, $lname, $mental_age) = split(/, /);
# creates a reference to an anonymous hash
# and stores that in the %ary hash, indexed by $i
$hash{$i}= {
FName => $fname,
LName => $lname,
MAge => $mental_age
};
}
foreach $key (keys %hash){ # loop thru the hash
$fname = $hash{$key}{FName}; # retrieve the firstname
$lname = $hash{$key}{LName}; # retrieve the last name
$mental_age = $hash{$key}->{MAge}; # mental age of subject
print ":$key:$fname $lname ($mental_age):\n";
}
__END__
01, Mike, Lacey, one
02, Kim, Lacey, forty
03, George, Lacey, four
[/tt]
What's an anonymous hash?
It's an ordinary hash, but without a name you create one as I've done above:
[tab][tab][color green]$some_scalar_variable[/color] = [color blue]{
[tab][tab][tab]FName => $fname,
[tab][tab][tab]LName => $lname,
[tab][tab]MAge => $mental_age
[tab]}[/color];
You can put it all on one line if you like, I just find it easier to read like this. The bit in blue is the part that creates the anonymouse hash.
The scalar variable (in green) is the reference. The nice thing about a reference is that you can put one in a list, either a hash as I've done here or a scalar array.
The Perl documentation says that you have to dereference the reference in order to use it - and that's part of what I found difficult. But it's not difficult, in the example above I just treated whatever was in the current element of %hash as if it were another hash.
I'd appreciate any comments you might have about this FAQ.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.