cooldood3490 cooldood3490 - 2 months ago 8
Perl Question

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

TLP TLP
Answer

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.

Comments