Perl:数组引用与匿名数组 [英] Perl: array reference versus anonymous array
问题描述
这可能是一个愚蠢的问题...以下代码分别输出@arrayref
和@arraycont
的内容.注意它们之间的区别以及它们的值分配方式.我知道匿名数组的作用,但是有人可以解释为什么存在差异吗?
This may be a silly question... The following code outputs the contents of @arrayref
and @arraycont
respectively. Note the difference between them and the way the values of them are assigned. I know what the anonymous array does, but can anybody explain why there is a difference?
非常感谢您.
@arrayref = ();
@array = qw(1 2 3 4);
$arrayref[0] = \@array;
@array = qw(5 6 7 8);
$arrayref[1] = \@array;
print join "\t", @{$arrayref[0]}, "\n";
print join "\t", @{$arrayref[1]}, "\n";
@arraycont = ();
@array = qw(1 2 3 4);
$arraycont[0] = [@array];
@array = qw(5 6 7 8);
$arraycont[1] = [@array];
print join "\t", @{$arraycont[0]}, "\n";
print join "\t", @{$arraycont[1]}, "\n";
输出
5 6 7 8
5 6 7 8
1 2 3 4
5 6 7 8
推荐答案
这将创建数组的浅副本:
$arraycont[0] = [@array];
这只是创建了对它的引用:
Whereas this just creates a reference to it:
$arrayref[0] = \@array;
自从您以后修改数组以来:
Since you later modify the array:
@array = qw(5 6 7 8);
arrayref
仍指向内存中的相同数组位置,因此在print语句中取消引用时,它会打印当前数组值5 6 7 8
.
arrayref
still points to the same array location in memory, and so when dereferenced in the print statements it prints the current array values 5 6 7 8
.
这篇关于Perl:数组引用与匿名数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!