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.
Perl术语让我困惑,这不是我的母语,所以请耐心等待。我会尝试使用正确的术语,但我会举一个例子来确保。
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.
所以我在变量$ foo中有一个哈希引用。让我们说$ foo - > {'bar'} - > {'baz'}是一个数组引用。那就是我可以通过将$ foo - > {'bar'} - > {'baz'} - > [0]分配给标量来获得数组的第一个成员。
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"
我收到错误“在script.pl第41行不是ARRAY参考”
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.
有什么我不理解的吗?有没有办法让第一个例子起作用?我试着用括号中的表达式将表达式包装在外面,但是这不起作用。提前谢谢你的帮助。
3 个解决方案
#1
11
$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: -
如果你用它的RHS替换你的$ myr in for循环,它看起来像: -
foreach (@{$foo->{'bar'}->{'baz'}})
{
#some code that deals with $_
}
#2
14
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不包含数组引用,因此错误。如果不省略引用表达式周围的可选currs,则不会出现优先级问题。
@{ $foo->{'bar'}->{'baz'} }
#3
3
It should look like
应该是这样的
foreach (@{$foo->{'bar'}->{'baz'}})
{
#some code that deals with $_
}
#1
11
$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: -
如果你用它的RHS替换你的$ myr in for循环,它看起来像: -
foreach (@{$foo->{'bar'}->{'baz'}})
{
#some code that deals with $_
}
#2
14
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不包含数组引用,因此错误。如果不省略引用表达式周围的可选currs,则不会出现优先级问题。
@{ $foo->{'bar'}->{'baz'} }
#3
3
It should look like
应该是这样的
foreach (@{$foo->{'bar'}->{'baz'}})
{
#some code that deals with $_
}