Perl的嵌套数组疑难解答

Perl的嵌套数组疑难解答,perl,multidimensional-array,Perl,Multidimensional Array,我的引用数组指向另一个数组时遇到问题。以下是我的代码片段: # @bah is a local variable array that's been populated, @foo is also initialized as a global variable $foo[9] = \@bah; # this works perfectly, printing the first element of the array @bah print $foo[9][0]."\n"; # thi

我的引用数组指向另一个数组时遇到问题。以下是我的代码片段:

# @bah is a local variable array that's been populated, @foo is also initialized as a global variable
$foo[9] = \@bah; 

# this works perfectly, printing the first element of the array @bah
print $foo[9][0]."\n"; 

# this does not work, nothing gets printed
foreach (@$foo[9]) {
    print $_."\n";
}

始终
严格使用
使用警告

@
取消引用优先,因此
@$foo[9]
期望
$foo
为数组引用,并从该数组中获取元素9。您需要
@{$foo[9]}
use strict
会提醒您正在使用
$foo
,而不是
@foo


有关一些易于记忆的取消引用规则,请参见。

就像ysth所说的,您需要使用大括号将
$foo[9]
正确地取消引用到它所指向的数组中

但是,您可能还想知道,使用
\@bah
直接引用数组。因此,如果以后更改
@bah
,您也将更改
$foo[9]

my @bah = (1,2,3);
$foo[9] = \@bah;
@bah = ('a','b','c');
print qq(@{$foo[9]});
这将打印
abc
,而不是
123code>

要仅从
@bah
复制值,请取消引用
$foo

@{$foo[9]} = @bah;