【发布时间】:2017-12-28 23:08:45
【问题描述】:
当我使用 @$arrayRef 或 @{$arrayRef} 取消引用数组时,它似乎创建了数组的副本。有没有正确的方法来取消引用数组?
这段代码...
sub updateArray1 {
my $aRef = shift;
my @a = @$aRef;
my $aRef2 = \@a;
$a[0] = 0;
push(@a, 3);
my $aRef3 = \@a;
print "inside1 \@a: @a\n";
print "inside1 \$aRef: $aRef\n";
print "inside1 \$aRef2: $aRef2\n";
print "inside1 \$aRef3: $aRef3\n\n";
}
my @array = (1, 2);
print "before: @array\n";
my $ar = \@array;
print "before: $ar\n\n";
updateArray1(\@array);
print "after: @array\n";
$ar = \@array;
print "after: $ar\n\n";
...有输出...
before: 1 2
before: ARRAY(0x1601440)
inside1 @a: 0 2 3
inside1 $aRef: ARRAY(0x1601440)
inside1 $aRef2: ARRAY(0x30c1f08)
inside1 $aRef3: ARRAY(0x30c1f08)
after: 1 2
after: ARRAY(0x1601440)
如您所见,@$aRef 创建了一个新的指针地址。
我发现解决此问题的唯一方法是仅使用参考:
sub updateArray2 {
my $aRef = shift;
@$aRef[0] = 0;
push(@$aRef, 3);
print "inside2 \@\$aRef: @$aRef\n";
print "inside2 \$aRef: $aRef\n\n";
}
updateArray2(\@array);
print "after2: @array\n";
$ar = \@array;
print "after2: $ar\n\n";
产生输出:
inside2 @$aRef: 0 2 3
inside2 $aRef: ARRAY(0x1601440)
after2: 0 2 3
after2: ARRAY(0x1601440)
是否可以在不复制整个数组的情况下取消引用指向数组的指针?还是我需要将其保留为参考形式并在我想使用它的任何时候取消参考?
【问题讨论】:
标签: arrays function perl subroutine dereference