Steve
Steve

Reputation: 347

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!

Upvotes: 1

Views: 459

Answers (3)

reflective_mind
reflective_mind

Reputation: 1525

Here my solution...just for fun and maybe even more concise. Not sure if you can compress this even further:

print join ' ', @$_, "\n" for @myhash{sort keys %myhash};

Works for arbitrary long value arrays in %myhash.

EDIT:

As simbabque pointed out in the comments, it can indeed be further compressed. Thanks for the hint!

say join ' ', @$_ for @myhash{sort keys %myhash}; # requires: use feature 'say';

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 185831

Another solution :

print map {  join(" ", @{ $myhash{$_} }, "\n") } sort keys %myhash;

(the concise way)

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86774

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";
}

Upvotes: 1

Related Questions