1

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!

3 Answers 3

2

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';
Sign up to request clarification or add additional context in comments.

2 Comments

Use say to make it shorter. But we are not on code golf. Short is not necessarily more concise. Sometimes it's just harder to read. ;-)
Very nice thanks! No code golf, just a little bit of perl spirit ;)
1

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

4 Comments

Exactly what I wanted... even when the number of array elements varies. Thank you very much!
Please do not post "thank you" comments. You express thanks by upvoting helpful answers and accepting the one that solves your problem (which you've already done). You should take the tour, visit the help center and read How to Ask.
He have 56k, I think he knows this ^^
No, the OP has 18
1

Another solution :

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

(the concise way)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.