Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does perl not allow me to dereference a member of a hash reference into an array?

Tags:

arrays

perl

Perl terms confuse me and it's not my native language, so bear with me. I'll try to use the right terms, but I'll give an example just to make sure.

So I have a hash reference in the variable $foo. Lets say that $foo->{'bar'}->{'baz'} is an array reference. That is I can get the first member of the array by assigning $foo->{'bar'}->{'baz'}->[0] to a scalar.

when I do this:

foreach (@$foo->{'bar'}->{'baz'})
{
    #some code that deals with $_
}

I get the error "Not an ARRAY reference at script.pl line 41"

But when I do this it works:

$myarr = $foo->{'bar'}->{'baz'};
foreach (@$myarr)
{
    #some code that deals with $_
}

Is there something I'm not understanding? Is there a way I can get the first example to work? I tried wrapping the expression in parentheses with the @ on the outside, but that didn't work. Thanks ahead of time for the help.

like image 219
Jason Thompson Avatar asked Oct 01 '12 18:10

Jason Thompson


2 Answers

It's just a precedence issue.

@$foo->{'bar'}->{'baz'}

means

( ( @{ $foo } )->{'bar'} )->{'baz'}

$foo does not contain an array reference, thus the error. You don't get the precedence issue if you don't omit the optional curlies around the reference expression.

@{ $foo->{'bar'}->{'baz'} }
like image 199
ikegami Avatar answered Oct 26 '22 22:10

ikegami


$myarr = $foo->{'bar'}->{'baz'};
foreach (@$myarr)
{
    #some code that deals with $_
}

If you replace your $myarr in for loop with its RHS, it looks like: -

foreach (@{$foo->{'bar'}->{'baz'}})
{
    #some code that deals with $_
}
like image 29
Rohit Jain Avatar answered Oct 26 '22 23:10

Rohit Jain