user3049982
user3049982

Reputation: 119

Iterate through an array of hashes of array in Perl?

I have trouble visualizing loops and have what I think is an array of hashes of arrays. Please correct me if I am misunderstanding this. I want to be able to loop through the below array and print each key's value.

The End results would print the elements like so:

name
version
pop
tart 

Unfortunately, I fall apart when I get to key three.

my @complex = (
    [
        {
            one   => 'name',
            two   => 'version',
            three =>  [qw( pop tart )],
        },
    ],
);

Here's what I've managed so far. I just don't know to handle key three within these loops.

for my $aref (@complex) {
    for my $href (@$aref) {
        for (keys %{$href}) {
            print "$href->{$_}\n";
        }
    }
}

Any help would be appreciated.

Upvotes: 3

Views: 174

Answers (1)

zdim
zdim

Reputation: 66873

What seems to be holding you back is that your hash has some values which are strings and some which are array references. You can find out which are which using ref and then print accordingly

for my $aref (@complex) {
    for my $href (@$aref) {
        for my $key (keys %{$href}) {
            my $refval = ref $href->{$key};
            if (not $refval) {              # not a reference at all
                print "$href->{$key}\n";
            } elsif ($refval eq 'ARRAY') {
                print "$_\n" for @{ $href->{$key} };
                #print "@{ $href->{$key} }\n";       # or all in one line
            } else {
                warn "Unexpected data structure: $refval";  
            }
        }
    }
}

For deeper structures, or those that you don't know, write a recursive procedure based on this. And then there are modules which will do it, as well.

Note that a careful consideration of what data structures to use pays off handsomely; it is one of the critical parts of design. On the other hand, once these complex data structures grow unwieldy, or rather if you estimate ahead of time that that can happen in the lifetime of the project, the answer is to switch to a class.

Upvotes: 4

Related Questions