列表是标量的集合,数组是存储列表的变量。更精确的说,列表指的是数据,而数组指的是变量。列表的值不一定放在数组里,但每一个数组变量都一定包含一个列表(即使列表可能是空的)。
列表与数组最主要的区别在于在标量环境中:数组被解释为其长度;而列表则被解释为其最后一个元素,此时列表相当于由逗号操作符组成的表达式。
测试代码:
1 2 3 4 5 | @array = ( "a", "b", "c" ); $num = @array; $list = ( "a", "b", "c" ); print "The number of array elements is "$num";nThe last element of list is "$list".n"; |
输出结果:
1 2 | The number of array elements is "3"; The last element of list is "c". |
对于子函数的返回值,同样如此。
测试代码:
1 2 3 4 5 6 7 8 9 10 11 | sub a { @arr = ( "a", "b", "c" ); #返回数组的元素个数 } sub b { ( "a", "b", "c" ); #返回列表的最后一个元素 } $array = a(); $list = b(); print "The number of array elements is "$array";nThe last element of list is "$list".n"; |
输出结果:
1 2 | The number of array elements is "3"; The last element of list is "c". |
明白了,但这是官方的解释吗?总觉得列表的定义怪怪的,主要是平时根本没注意到……数组被解释为长度倒是经常用
上面的解释好像是错误的!
使用perldoc -q list可以查询到以下解释:
What is the difference between a list and an array?
An array has a changeable length. A list does not. An array is
something you can push or pop, while a list is a set of values. Some
people make the distinction that a list is a value while an array is a
variable. Subroutines are passed and return lists, you put things into
list context, you initialize arrays with lists, and you “foreach()”
across a list. “@” variables are arrays, anonymous arrays are arrays,
arrays in scalar context behave like the number of elements in them,
subroutines access their arguments through the array @_, and
“push”/”pop”/”shift” only work on arrays.
As a side note, there’s no such thing as a list in scalar context.
When you say
$scalar = (2, 5, 7, 9);
you’re using the comma operator in scalar context, so it uses the
scalar comma operator. There never was a list there at all! This
causes the last value to be returned: 9.
晕倒……
非常感谢您写的好文章, 学习好多.
能有所帮助就好^_^
PS:正文中有一定的错误,注意看一下文章后面的评论!
下面的一些英文注释理解的不是很明白, 但是将一个列表赋值给一个标量变量的确是有问题的.
您能否将最后那句解释下?
可以看一下这篇解释,我觉得说到点子上了:
http://blogs.perl.org/users/steven_haryanto/2012/09/the-comma-operator.html