Young Young - 2 months ago 8
Perl Question

Perl: How to access a hash with array values in a loop?

I've defined a hash with arrays as values:

%myhash = ( 'key1' => [ 'key1value1', 'key1value2' ],
'key2' => [ 'key2value1', 'key2value2' ],
.......
'key100' => [ 'key100value1', 'key100value2' ] );


How can we access the values of each key using a loop?

Basically, I want to do something like:

print "$myhash{'key1'}->[0] and $myhash{'key1'}->[1]\n";
print "$myhash{'key2'}->[0] and $myhash{'key2'}->[1]\n";
.......
print "$myhash{'key100'}->[0] and $myhash{'key100'}->[1]\n";


to print those two array values of each key in separate lines.

I've tried using an index in for/while loops with no success.

Thanks for any suggestions in advance!

Answer

Here's one way:

%myhash = ( 'key1' => [ 'key1value1', 'key1value2' ],
            'key2' => [ 'key2value1', 'key2value2' ],
            'key3' => [ 'key3value1', 'key3value2' ] );

for my $k (sort keys %myhash)
{
    print "$myhash{$k}->[0] $myhash{$k}->[1]\n";
}

If the number of array elements varies:

for my $k (sort keys %myhash)
{
    for my $v (@{$myhash{$k}})
    {
        print "$v ";
    }
    print "\n";
}