Perl的数组列表VS [英] Perl array vs list

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

问题描述

我有两个数据结构在Perl:

I have two data structures in Perl:

数组:

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

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

给我下面的输出:

Giving me the following output:

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列表是没有数据结构,它们是在源$ C ​​$ C位置,被周围的环境来确定。列表是基本上是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";
}

由于要在整个阵列上操作,而不只是参考,将 @ $阵列前面其中取消引用存储数组引用。

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的数组列表VS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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