可以在 Perl 中将一个数组的地址分配给另一个吗? [英] Assign address of one array to another in Perl possible?
问题描述
在以下 C# 代码中:
In the following C# code:
int[] X = new int[2];
X[0] = 1;
X[1] = 2;
int[] Y = X;
X[1] = 3;
执行此操作后,Y[1] 也将为 3,因为操作 Y = X 不会进行克隆,而是将 X 指向的内容的引用或指针分配给 Y.
After this executes, Y[1] will also be 3 since the operation Y = X does not do a clone but rather assigns the reference or pointer of what X is pointing at to Y.
如果在 Perl 5 下尝试相同的操作:
If the same operation is tried under Perl 5:
my @X = (1, 2);
my @Y = @X;
$X[1] = 3;
与 C# 不同的是,Y[1] 不是 3,而是 2,这表明 Perl 在@Y = @X 操作后对数组进行了复制.
Unlike C#, Y[1] is not 3, but still 2, which indicates that Perl makes a copy of the array after the @Y = @X operation.
所以,我的问题是 - 有没有办法使用另一个 Perl 数组的引用来分配或初始化 Perl 5 数组,以便它们都指向相同的数据?我已经了解引用并尝试取消引用对数组的引用,但这也会生成一个副本.我也知道使用对数组的引用可以解决我想要做的大部分事情,所以我不需要任何说明如何使用引用的答案.
So, my question is - is there any way to assign or initialize a Perl 5 array with the reference of another Perl array so that they both point to the same data? I already know about references and have tried dereferencing a reference to an array, but that too makes a copy. I'm also aware that using a reference to an array will solve most of what I'm trying to do, so I don't need any answers showing how to work with references.
推荐答案
您在 C# 程序中使用了引用,而不是在 Perl 程序中.如果您在 Perl 中使用引用,则效果相同.
You're using a reference in the C# program, but not in the Perl program. It works the same if you use a reference in Perl.
my $X = [ 1, 2 ];
my $Y = $X;
$X->[1] = 3;
print "@$Y\n"; # 1 3
或
my @X = ( 1, 2 );
my $Y = \@X;
$X[1] = 3;
print "@$Y\n"; # 1 3
您也可以创建别名.
use Data::Alias qw( alias );
my @X = ( 1, 2 );
alias my @Y = @X;
$X[1] = 3;
print "@Y\n"; # 1 3
这篇关于可以在 Perl 中将一个数组的地址分配给另一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!