Arribah
Arribah

Reputation: 78

Dereferencing hashes of hashes in Perl

I'm trying to collect the values that I store in a hash of hashes, but I'm kinda confused in how perl does that. So, I create my hash of hashes as follows:

 my %hash;
 my @items;

 #... some code missing here, generally I'm just populating the @items list 
 #with $currentitem items

 while (<FILE>) { #read the file

         ($a, $b) = split(/\s+/,$_,-1);
         $hash{$currentitem} => {$a => $b};
         print $hash{$currentitem}{$a} . "\n";#this is a test and it works
}

The above code seems to work. Now, to the point: I have an array @items, which keeps the $currentitem values. And I want to do something like this:

@test = keys %hash{ $items[$num] };

So that I can get all the key/value pairs for a specific item. I've tried the line of code above, as well as

 while ( ($key, $value) = each( $hash{$items[$num]} ) ) {

      print "$key, $value\n";
 }

I've even tried to populate the hash as follows:

$host{ "$currentcustomer" }{"$a"} => "$b";

Which seems to be more correct according to the various online sources I've met. But still, I can't access the data inside that hash... Any ideas?

Upvotes: 2

Views: 228

Answers (2)

dan1111
dan1111

Reputation: 6566

I am confused by you saying that this works:

$hash{$currentitem} => {$a => $b};

That shouldn't work (and doesn't work for me). The => operator is a special kind of comma, not an assignment (see perlop). In addition, the construct on the right makes a new anonymous hash. Using that, a new anonymous hash would overwrite the old one for each element you tried to add. You would only ever have one element for each $currentitem.

Here is what you want for assignment:

$hash{$currentitem}{$a} = $b;

And here is how to get the keys:

keys %{ $hash{ $items[$num] } };

I suggest reading up on Perl references to get a better handle on this. The syntax can be a bit tricky at first.

Upvotes: 2

Dallaylaen
Dallaylaen

Reputation: 5308

Long answer is in perldoc perldsc.

Short answer is:

keys %{ $expr_producing_hash_ref };

In your case I believe it's

keys %{ $hash{$items[$num]} }; 

Upvotes: 1

Related Questions