PDA

View Full Version : Question about a hash of a hash


Dustfinger
07-08-2008, 10:20 PM
I have a hash, %db, and inside it each value is another hash; a hash of hashes.
I'm trying to get a list of the keys of the hash that is returned when you call $db{'someKey'}, but I'm having trouble doing so. Here's the code I've tried:


print "$db{'someKey'}\n";
%temp = $db{'someKey'};
@lookThrough = keys(%temp);
foreach(@lookThrough) {
print "$_\n";
}


@lookThrough being the list of the keys I'm trying to get. But when I run this code, I get the output:
HASH(0x96f5a0)
HASH(0x96f5a0)

The first line is good, it means $db{'someKey'} returns a hash, which is what's expected. But for some reason the keys(%temp) part is just returning %temp, instead of an array of keys. Can anyone help me out with this?

oesxyl
07-08-2008, 10:29 PM
try this:

print $db{'someKey'},"\n";
%temp = %$db{'someKey'};
@lookThrough = keys(%temp);
foreach(@lookThrough) {
print "$_\n";
}


regards

Dustfinger
07-09-2008, 12:06 AM
I get a syntax error near '$db{'' :-/

oesxyl
07-09-2008, 12:44 AM
I get a syntax error near '$db{'' :-/
sorry, is my fault


print $db{'someKey'},"\n";
%temp = %{$db{'someKey'}};
@lookThrough = keys(%temp);
foreach(@lookThrough) {
print "$_\n";
}


regards

KevinADC
07-09-2008, 04:37 AM
or a little shorter, the %temp is not necessary:

@lookThrough = keys ( %{ $db{'someKey'} } );
foreach (@lookThrough) {
print "$_\n";
}

Or if you really don't need the array but only want to see the keys:

foreach ( keys ( %{ $db{'someKey'} } ) ) {
print "$_\n";
}

KevinADC
07-09-2008, 04:41 AM
BTW:

this is called dereferencing:

%{$foo} (hash)
@{$foo} (array)
${$foo} (scalar)
$foo->() (code)

which is necessary to get to the data stored in references.

Dustfinger
07-13-2008, 05:24 PM
Thanks oesxyl and Kevin, I got it working now :P

And thanks for pointing out that it's called dereferencing, I was trying to find more information but had no idea what I was looking for >__<