Perl 中美元符号和数字符号如何一起工作?
今天遇到一个问题,要求我在perl中确定数组的最大索引。我曾经这样做过:
my @array = (1, 2, 3);
print $array[@array - 1];
但今天我偶然发现了这段代码:
my @array = (1, 2, 3);
print $array[$#array];
我在文档中找不到任何关于此事的内容。 $#
构造到底是什么?那是运营商吗?它是如何工作的,它比第一段代码更快吗?它总是返回最大数组索引吗?它是否已弃用?
我知道这是很多问题,但它们都可以用一个来概括,这就是我真正想知道的:它是如何工作的?
Today I have encountered a problem that required me to determine the maximum index of an array in perl. I used to do it this way:
my @array = (1, 2, 3);
print $array[@array - 1];
But today I have stumbled upon this code:
my @array = (1, 2, 3);
print $array[$#array];
I couldn't find anything on that matter in the docs. What exactly is that $#
construct? Is that an operator? And how does it work, is it faster than the first piece of code? Does it always return the maximum array index? Is it deprecated or not?
I know that's a lot of questions, but they all can be summed up by one, and that's what I really want to know: How does it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这记录在 perldoc perldata,“标量值”部分中。简而言之,
$#array
是@array
的最后一个索引。至于它是如何工作的——它有点像一个运算符,但只有$
和@
是运算符。将其视为特殊语法。数组的最后一个索引恰好“有一个名称”。它是一个可以读取和赋值的变量。This is documented in perldoc perldata, section "Scalar Values". In short,
$#array
is the last index of@array
. As for how it works — it's sort of like an operator, but only as much as$
and@
are operators. Think of it as special syntax. The last index of an array just happens to "have a name". It's a variable that you can read from and assign to.perldata 中的第一个示例中提到了该用法。它表示数组中最后一项的索引。
顺便说一句,您还可以用来
获取最后一项。
The use is mentioned in first example in perldata. It denotes index of last item in the array.
Btw, you can also use
to get last item.
这给了你最后一个索引。它记录在 perldata - http://perldoc.perl.org/perldata.html
That gives you the last index. It's documented in perldata - http://perldoc.perl.org/perldata.html