Why doesn't perl let me look up a hash link element in an array?

Perl's conditions confuse me, and it is not my native language, so bear with me. I will try to use the correct conditions, but I will give an example to make sure.

So, I have a hash reference in the variable $ foo. Suppose $ foo → {'bar'} → {'baz'} is an array reference. That is, I can get the first member of the array by assigning $ foo → {'bar'} → {'baz'} → [0] scalar.

when i do this:

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

I get the error "No ARRAY link on 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 don't understand? Is there a way to make the first example work? I tried to wrap the expression in parentheses with @ outside, but that didn't work. Thanks in advance for your help.

+6
source share
3 answers
 $myarr = $foo->{'bar'}->{'baz'}; foreach (@$myarr) { #some code that deals with $_ } 

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

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

This is just a priority issue.

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

means

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

$foo does not contain an array reference, therefore an error. You do not get a priority problem unless you omit the optional curls around the reference expression.

 @{ $foo->{'bar'}->{'baz'} } 
+14
source

It should look like

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

Source: https://habr.com/ru/post/926693/


All Articles