cooldood3490
cooldood3490

Reputation: 2498

Looping through hash of arrays in Perl

I have a hash of arrays, as follows:

my %hash = (
234 => ["Larry", "Curly", "Moe"],
235 => ["bb", "ab", "aa", "ab", "bb"],
236 => ["aa", "ab", "bb", "aa", "bb"],
)

For each key in my hash, I would like to loop through each element of the array, assign that to a scalar variable so that I can process it, then move onto the next element of the array. Once I have processed all the elements of the array for a key, I want to onto the next key and individually process all of the elements of its array, and so on.

I found and modified a snippet of code that iterates over the hash values (the array of each key in this case). Then I have a nested for-loop, that iterates over each element of that array. However, it's not doing what I expect it to.

for my $value (values %hash) {
    for (@$value) {
        my $index = shift($_);
       #process index
    }
}

Error Message Not an ARRAY reference at [line number]

For example, for the first iteration, I want $index to equal Larry so that I can process it. Next iteration, I want $index to equal Curly so that I can process it. Next iteration, $index should equal Moe, process it. Next iteration, $index should equal bb, and so on.

There may be a better function than shift. The shift function takes the first element off of the array. I want the hash of arrays to retain it's values so that I don't have to repopulate the hash of arrays.

thanks

Upvotes: 4

Views: 15940

Answers (2)

user3138373
user3138373

Reputation: 523

If you want to loop through hash of arrays you can do some thing like this

#!/usrbin/perl -w
use strict;
use warnings;
use Data::Dumper;


my %hash = (
234 => ["Larry", "Curly", "Moe"],
235 => ["bb", "ab", "aa", "ab", "bb"],
236 => ["aa", "ab", "bb", "aa", "bb"],
);

foreach (keys %hash){
    foreach my $array(@{$hash{$_}}){
        ##do something with $array;
    }
}

Here $array will hold your array values one at a time for a particular key.

Thanks

Upvotes: 1

TLP
TLP

Reputation: 67910

The problem is that your list in @$value is already a list of your array elements, not arrays. Which is why you cannot use shift on it. All you need is:

for my $value (values %hash) {
    for my $index (@$value) {  # "Larry", "Curly", "Moe" etc
       ....
       #process index
    }
}

You probably don't want to use shift on your array anyway, since that will delete entries from your original structure.

Upvotes: 9

Related Questions