我的引用数组指向另一个数组时遇到了问题。下面是我的代码片段:
# @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";
}发布于 2011-06-01 03:31:58
总是use strict;和use warnings;。
@解引用具有优先权,因此@$foo[9]希望$foo是一个数组引用,并从该数组中获取元素9。你想要@{$foo[9]}。use strict会提醒您正在使用$foo,而不是@foo。
有关取消引用的一些易于记忆的规则,请参见http://perlmonks.org/?node=References+quick+reference。
发布于 2011-06-01 03:45:24
就像ysth所说的,你需要使用大括号来正确地将$foo[9]引用到它所指向的数组中。
但是,您可能还想知道,使用\@bah时,您直接引用了数组。因此,如果稍后更改@bah,您也将更改$foo[9]:
my @bah = (1,2,3);
$foo[9] = \@bah;
@bah = ('a','b','c');
print qq(@{$foo[9]});这将打印a b c,而不是1 2 3。
仅从@bah复制值,而不是取消引用$foo
@{$foo[9]} = @bah;https://stackoverflow.com/questions/6192493
复制相似问题