开发者

Nested Array Troubleshoot for Perl

I am having trouble with my array of references which point to another array. Here's a snippet of my code:

# @bah is a local variable array that's been populated, @foo is also initialized as开发者_JAVA百科 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";
}


Always use strict; and use warnings;.

The @ dereference takes precedence, so @$foo[9] expects $foo to be an array reference and gets element 9 from that array. You want @{$foo[9]}. use strict would have alerted you that $foo was being used, not @foo.

For some easily memorizable rules for dereferencing, see http://perlmonks.org/?node=References+quick+reference.


Like ysth says, you need to use braces to properly dereference $foo[9] into the array it points to.

You may however also want to be aware that using \@bah you are directly referencing the array. So that if change @bah later on, you will change $foo[9] as well:

my @bah = (1,2,3);
$foo[9] = \@bah;
@bah = ('a','b','c');
print qq(@{$foo[9]});

This will print a b c, and not 1 2 3.

To only copy the values from @bah, instead dereference $foo:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜