Jason Thompson
Jason Thompson

Reputation: 4833

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

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.

Upvotes: 6

Views: 293

Answers (3)

ikegami
ikegami

Reputation: 385897

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'} }

Upvotes: 14

Rohit Jain
Rohit Jain

Reputation: 213271

$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 $_
}

Upvotes: 11

Galimov Albert
Galimov Albert

Reputation: 7357

It should look like

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

Upvotes: 3

Related Questions