Question

%HoH = (
Group1=> {
    member1=> "fred",
    member2=> "barney",
},
 Group2 => {
    member1   => "george",
    member2   => "jane",  
},

);

How can I access second value or second key of HoH I want to access member2 of each group keys and their associated values.I don't know my key name , I just know it is second key

   foreach $key (keys %HoH){
        foreach $value (keys %{$HoH{$key}}){
            print $key."\n";
         }
   }
Was it helpful?

Solution

You cannot access neither "second key" nor "second value" because there's no particular order of hash elements. print Dumper(\%HoH); will likely give you another order of hash elements than the order you initializer used. You should use hash of arrays if you want a particular order.

my %HoH = (
    Group1=> [ "fred", "barney" ],
    Group2 => [ "george", "jane" ]
);

After that you can access "fred" as $HoH{Group1}->[0] and "jane" as $HoH{Group2}->[1].

OTHER TIPS

foreach my $key (keys %HoH)  
{  
    foreach my $value (keys %{$HoH{$key}})  
    {  
        if($value eq "member2") 
        {  
            print $HoH{$key}{$value}."\n";  
        }  
    }
} 

The following prints the value of each member2 key (see also perldoc perldsc):

use warnings;
use strict;

my %HoH = (
Group1=> {
    member1=> "fred",
    member2=> "barney",
},
 Group2 => {
    member1   => "george",
    member2   => "jane",  
},

);

for (keys %HoH) {
    print "$HoH{$_}{member2}\n";
}

As mentioned above, you don't know that you actually want the second key, because you have no way of determining the order that the hash keys were stored in. keys is guaranteed to return the same order for a consistent set of keys, but not likely in the order you declared them.

You can however, look into Tie::IxHash for an ordered hash. But if you really want to relate the data between two hashes, you probably need to rethink the structure, rather than rely on order.

Also, $member[$i-1] is better than $hash{'member'.$i}. As well as being faster, it's just better structure. If you find yourself with "indexing" keys, it's a good indication that you want a list and not a hash.

This just seems to make more sense for the structure of your data from what you're showing me:

my @groups 
    = ( [ qw<fred   barney> ]
      , [ qw<george jane>   ]
      );

By another way.

%HoH = (
Group1=> {
    member1=> "fred",
    member2=> "barney",
},
 Group2 => {
    member1   => "george",
    member2   => "jane",
},
);

print map { "$HoH{$_}{'member2'}\n" } keys %HoH;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top