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 $_
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With