mhearse has asked for the wisdom of the Perl Monks concerning the following question:

I have a data structure which resembles:
$VAR1 = { 'key' => { 'data' => [ [ 'Element1', 'Element2', 'Element3' ], [ 'Element1', 'Element2', 'Element3' ] ] }
How can I iterate over the anonymous array in the data value? I thought this would work, but it doesn't:
for my $elmt (@{$book->{$key}{data}}) { .... }

Replies are listed 'Best First'.
Re: Help dereferencing a data structure
by NetWallah (Canon) on Mar 27, 2008 at 05:47 UTC
    You have a reference to a HOHOAOA, and need to de-reference it so:
    use strict; use warnings; my $book = { 'key' => {'data' => [ [ 'Element1', 'Element2', 'Element3' ], [ 'Element1', 'Element2', 'Element3' ] ] } }; for my $key (keys %$book){ for my $data ( keys %{ $book->{$key} } ){ for my $inner_array_ref ( @{ $book->{$key}{$data} } ) { ## Array above can also be written as: @{ $book->{$key}-> +{$data} } print "$key\t$data\t@$inner_array_ref\n"; } } }

         "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom

Re: Help dereferencing a data structure
by planetscape (Chancellor) on Mar 27, 2008 at 09:32 UTC
Re: Help dereferencing a data structure
by wade (Pilgrim) on Mar 27, 2008 at 04:08 UTC
    There are a couple issues. One is that you had references and you treated one as a hash. Also, I think you meant "key" when you used $key (of course, if $key eq "key"...).

    This code seems to work.

    use strict; use warnings; { foreach my $datum (@{$var1->{"key"}->{"data"}->[0]}) { print "$datum\n"; } }
    --
    Wade