简体   繁体   中英

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.

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

It should look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM