views:

116

answers:

3

If I do the following, it works fine:

print $ref->{element}->[0]->{data};

I would like to see how many references are in the array so that I can loop through them, but I am having a hard time doing that.

Here is the code I have tried, but it doesn't work:

my @array = @$ref->{element};

foreach(@array) {
    print $_->{data};
}

I get an "Not an ARRAY reference" error

A: 

As a general aid in debugging, give Data::Dumper a look. It's invaluable for poking about in the innards of data structures.

vinny
I am using that, but that only tells me there is an array there (which is how i know that). Since I can access that array and print values further down, I know that isn't the issue. What I need is to be able to loop through that array.
Jeremey
+8  A: 

Hashes of lists are tricky that way. @$ref->{element} gets parsed as (@$ref)->{element}, dereferencing $ref instead of $ref->{element}.

Try

my @array = @{$ref->{element}}

or

my $size = scalar @{$ref->{element}}

Gory details in perllol.

mobrule
Thanks, works great!
Jeremey
Technically you don't need to use `scalar` to get the length, but I would probably leave it in.
Brad Gilbert
A: 

In addition to the @mobrule answer:

You can also shorten the expression a bit by omitting the '->' operator (good for long expressions):

print $ref->{element}[0]{data};

and

my @array = @{$$ref{element}};
eugene y