在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]?

查看:70
本文介绍了在Perl中,使用@a [$ i]访问数组元素与使用$ 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 a number of elements.

就这样

  • 当您要访问单个元素时,应使用$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屋!

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