列表和数组有什么区别? [英] What is the difference between lists and arrays?
问题描述
在此页面上,该页面显示了如何初始化数组,如果向下滚动,请点击在名为列表"的部分中,它解释"了什么是列表以及它们与数组的区别.
On this page, it shows how to initialize an array, and if you scroll down a bit, under the section called "The Lists" it "explains" what lists are and how they're different from arrays.
除了它使用的示例与声明数组完全相同之外,没有任何解释.
Except it uses an example that's just exactly the same as declaring an array, and doesn't explain it whatsoever.
有什么区别?
推荐答案
看看 perldoc -q "list and an array"
.最大的区别是数组是一个变量,但是Perl的所有数据类型(标量,数组和哈希)都可以提供一个 list ,它只是一个有序的标量.
Take a look at perldoc -q "list and an array"
. The biggest difference is that an array is a variable, but all of Perl's data types (scalar, array and hash) can provide a list, which is simply an ordered set of scalars.
考虑此代码
use strict;
use warnings;
my $scalar = 'text';
my @array = (1, 2, 3);
my %hash = (key1 => 'val1', key2 => 'val2');
test();
test($scalar);
test(@array);
test(%hash);
sub test { printf "( %s )\n", join ', ', @_ }
输出此
( )
( text )
( 1, 2, 3 )
( key2, val2, key1, val1 )
Perl子例程将 list 作为其参数.在第一种情况下,列表为空;在第二个中,它只有一个元素( $scalar)
;在第三个列表中,列表的大小与@array
相同,并且包含( $array[0], $array[1], $array[2], ...)
,最后一个列表是两次(与%hash
中的元素数量一样是错误),并且包含( 'key1', $hash{key1}, 'key2', $hash{key2}, ...)
A Perl subroutine takes a list as its parameters. In the first case the list is empty; in the second it has a single element ( $scalar)
; in the third the list is the same size as @array
and contains ( $array[0], $array[1], $array[2], ...)
, and in the last it is twice as bug as the number of elements in %hash
, and contains ( 'key1', $hash{key1}, 'key2', $hash{key2}, ...)
.
很显然,可以通过多种方式提供该列表,包括混合标量变量,标量常量以及子例程调用的结果,例如
Clearly that list can be provided in several ways, including a mix of scalar variables, scalar constants, and the result of subroutine calls, such as
test($scalar, $array[1], $hash{key2}, 99, {aa => 1, bb => 2}, \*STDOUT, test2())
我希望很明显,这样的列表与数组非常不同.
and I hope it is clear that such a list is very different from an array.
将数组视为列表变量是否有帮助?区分标量文字和标量变量的问题很少.例如:
Would it help to think of arrays as list variables? There is rarely a problem distinguishing between scalar literals and scalar variables. For instance:
my $str = 'string';
my $num = 99;
很明显,'string'
和99
是文字,而$str
和$num
是变量.这里的区别是相同的:
it is clear that 'string'
and 99
are literals while $str
and $num
are variables. And the distinction is the same here:
my @numbers = (1, 2, 3, 4);
my @strings = qw/ aa bb cc dd /;
其中(1, 2, 3, 4)
和qw/ aa bb cc dd /
是列表文字,而@numbers
和@strings
是变量.
where (1, 2, 3, 4)
and qw/ aa bb cc dd /
are list literals, while @numbers
and @strings
are variables.
这篇关于列表和数组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!