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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

hashes of hashes 2

Status
Not open for further replies.

m4trix

Vendor
Jul 31, 2002
84
CA
quick question.

Say I have a hash of hashes, like this for example:

$DB{$membername}{'IP'} = $ipaddress;
$DB{$membername}{'ID'} = $membrID;
$DB{$membername}{'GRP'} = $membrgroup;

My question is simply out of my own curiosity, and doesn't really have any use that I can think of, but let's say we go

foreach $val (sort values %DB){
print "$val\n";
}

that should print the value for each of the first hash right? When I run it it prints things like:
HASH(0x80fa52c)
HASH(0x80fa568)
HASH(0x80fa5a4)

Which makes sense, because the value of each hash IS a hash right? Well, how could it to print the values using (sort values %DB) ?

I've tried going:
foreach %val (sort values %DB){
foreach $key (sort keys %val){
print "- $key";
}
print "\n";
}

But that doesn't work either. If it can be done how would I do it?
(and yes, I realize that using (keys %DB) would work easily)

thanks
 
$DB{$membername}{'IP'} = $ipaddress;
In this case, $DB{$membername} is actually a reference to a hash, not actually a hash. You'd need to do one of the deferencing methods, like %{$DB{$membername}} to get the actual hash at that point. Lets take it a level deeper.
Code:
$hash{mammal}{dog} = 'fido';
$hash{mammal}{cat} = 'ally';
$hash{reptile}{lizard} = 'blue';

foreach $animal (keys %hash)
{
     foreach $type (keys %{$hash{$animal}})
     {
          print "$animal - $type - $hash{$animal}{$type}\n";
     }
}
And you'd be surprised how useful hashes of hashes of hashes can be. Me and an old roommate made a knowledge base that drew fairly basic inferences. You tell it 'a dog is a small mammal.' and 'Frank is a fat dog.' then ask 'Is Frank a mammal?' and it knows Frank is a fat dog, and a fat dog is a dog, and a dog is a small mammal, and a small mammal is a mammal, so the answer is 'yes'. All done with many many many levels of hashes of hashes.

Looking back at it, I'm not sure this is what you asked at all. Today has been kind of fuzzy. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top