在 Perl 中,使用@a[$i] 访问数组元素与使用 $a[$i] 有什么区别? [英] In Perl, what is the difference between accessing an array element using @a[$i] as opposed to using $a[$i]?
问题描述
我遵循的基本语法教程没有说明这一点:
Basic syntax tutorials I followed do not make this clear:
使用前一个或后一个下标符号访问数组之间是否有任何实际/哲学/上下文相关/棘手的区别?
Is there any practical/philosophical/context-dependent/tricky difference between accessing an array using the former or latter subscript notation?
$ perl -le 'my @a = qw(io tu egli); print $a[1], @a[1]'
两种情况下的输出似乎相同.
The output seems to be the same in both cases.
推荐答案
$a[...] # array element
返回由索引表达式标识的一个元素,并且
returns the one element identified by the index expression, and
@a[...] # array slice
返回索引表达式标识的所有元素.
returns all the elements identified by the index expression.
因此,
- 当您打算访问单个元素以将此信息传达给读者时,您应该使用
$a[EXPR]
.事实上,如果您不这样做,您可能会收到警告. - 当您打算访问许多元素或可变数量的元素时,您应该使用
@a[LIST]
.
- You should use
$a[EXPR]
when you mean to access a single element in order to convey this information to the reader. In fact, you can get a warning if you don't. - You should use
@a[LIST]
when you mean to access many elements or a variable number of elements.
但这并不是故事的结局.您询问了实际和棘手(微妙?)的差异,但还没有提到:数组元素的索引表达式是在标量上下文中计算的,而数组切片的索引表达式是在列表上下文中计算的.
But that's not the end of the story. You asked for practical and tricky (subtle?) differences, and there's one noone mentioned yet: The index expression for an array element is evaluated in scalar context, while the index expression for an array slice is evaluated in list context.
sub f { return @_; }
$a[ f(4,5,6) ] # Same as $a[3]
@a[ f(4,5,6) ] # Same as $a[4],$a[5],$a[6]
这篇关于在 Perl 中,使用@a[$i] 访问数组元素与使用 $a[$i] 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!