Perl 数组与列表 [英] Perl array vs list

查看:36
本文介绍了Perl 数组与列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Perl 中有两个数据结构:

I have two data structures in Perl:

一个数组:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

给我以下输出:

1
2
3

还有一个列表:

my @array = [ "1", "2", "3"];                                            

for $elem (@array) {
    print $elem."\n";
}

给出以下输出:

ARRAY(0x9c90818)

显然,我想在两种情况下迭代元素,但为什么第二个解决方案只给我这个数组的引用?

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

推荐答案

Perl 中的列表不是数据结构,它们是源代码中的位置,由它们周围的上下文决定.列表基本上是 Perl 用来移动数据的瞬态结构.您可以使用 Perl 的所有语法与它们交互,但不能将它们作为数据类型使用.最接近列表的数据类型是数组.

Lists in Perl are not data structures, they are positions in the source code, determined by the context around them. Lists are basically the transient structures that Perl uses to move data around. You interact with them with all of Perl's syntax, but you can not work with them as a data type. The data type that is closest to a list is an array.

my @var    =    (1, 2, 3);  # parens needed for precedence, they do not create a list
   ^ an array    ^ a list

say 1, 2, 3;
    ^ a list

say @var;
    ^ a list (of one array, which will expand into 3 values before `say` is called)

当您编写 [1, 2, 3] 时,您所做的是创建一个标量数组引用.该数组引用使用列表 1, 2, 3 初始化,这与创建命名数组并引用它相同:

When you write [1, 2, 3] what you are doing is creating a scalar array reference. That array reference is initialized with the list 1, 2, 3, and it is the same as creating a named array and taking a reference to it:

[1, 2, 3]   ~~   do {my @x = (1, 2, 3); \@x}

由于 [...] 构造创建了一个标量,您应该将它保存在一个标量中:

Since the [...] construct creates a scalar, you should hold it in a scalar:

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

for my $elem (@$array) {   # lexical loop variable
    print $elem."\n";
}

因为您想对整个数组进行操作,而不仅仅是引用,所以您在 $array 前面放置了一个 @,它取消引用存储的数组引用.

Since you want to operate on the whole array, and not just the reference, you place a @ in front of the $array which dereferences the stored array reference.

这篇关于Perl 数组与列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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