我能说出在Perl匿名数组? [英] Can I name an anonymous array in Perl?

查看:162
本文介绍了我能说出在Perl匿名数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/perl -w

use strict;

my $aref = [1, 2, 3];
my @a = @$aref;              # this line
$a[1] = 99;
print "aref = @$aref\n";
print "a = @a\n";

产生输出:

aref = 1 2 3
a = 1 99 3

输出显示 @a @ $ AREF 不是指同一个数组。

标记行是我的问题所在。标 $ AREF 的值是一个匿名数组的引用。在标记线,我希望能够使数组变量 @a 指的是阵列,但发生的事情是,匿名数组被复制和 @a 指的是匿名数组的一个副本。分配和打印报表显示这一点。

The marked line is where my problem lies. The value of scalar $aref is a reference to an anonymous array. In the marked line I was hoping to be able to make the array variable @a refer to that array, but what happens is that the anonymous array is copied and @a refers to a copy of the anonymous array. The assignment and print statements show this.

据我了解,当你分配给数组赋值的右手边是一个列表上下文,因此 @ $ AREF 被胁迫的元素列表。有没有办法给名称 @a $ AREF

I understand that when you assign to an array the right hand side of the assignment is a list context, so the @$aref is coerced to a list of its elements. Is there a way to give the name @a to the array referred to by $aref?

推荐答案

我不知道为什么的你会想这样做?我presume这是一个性能问题,但通常的解决办法是参照各地传递数据。这是一样容易写 $ aref-> [1] $ A [1]

I wonder why would you want to do this? I presume it's a performance issue, but the usual solution is to pass your data around by reference. It is just as easy to write $aref->[1] as $a[1]

您可以的别名的你在包符号表通过参考分配给类型团,但别名必须是一个包变量

You could alias your reference in the package symbol table by assigning to the typeglob, but the alias must be a package variable

use strict;
use warnings;

my $aref = [1, 2, 3];

our @a;
*a = $aref;

$a[1] = 99;

print "aref = @$aref\n";
print "a    = @a\n";

输出

aref = 1 99 3
a    = 1 99 3

有许多模块,提供了一个很好的语法,让你别名词法变量

There are a number of modules that offer a nice syntax and allow you to alias lexical variables

下面是一个使用一个版本的 词汇::别名 具有混叠词法变量的优点,并且可以比分配给类型团更健壮。 数据::别名在一个非常相似的方式工作。输出是相同于上述

Here's a version that uses Lexical::Alias which has the advantage of aliasing lexical variables, and could be more robust than assigning to typeglobs. Data::Alias works in a very similar way. The output is identical to the above

use strict;
use warnings;

use Lexical::Alias qw/ alias_r /;

my $aref = [1, 2, 3];

alias_r $aref, \my @a;

$a[1] = 99;

print "aref = @$aref\n";
print "a    = @a\n";

另一种方法是使用别名而不是 alias_r

alias @$aref, my @a;

这篇关于我能说出在Perl匿名数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆