Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I create and use a hash of hashes?

Little tricks

How do I create and use a hash of hashes?

by  MikeLacey  Posted    (Edited  )
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.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top