在数组中查找最后一个元素的索引
大多数Perl程序员都知道,为了找到数组的大小,数组必须在类似这样的标量上下文中调用
# Declare the array
my @numbers_array = (41,67,13,9,62);
# Get the array size
my $size_of_array = @numbers_array;
这种理解可能导致程序员将标量上下文应用于数组以访问其最后一个元素(因为数组是从0开始的,所以需要减去1)。
print $numbers_array[@numbers_array - 1];
# 62
最后一个索引变量
Perl为数组有一个“最后一个索引”变量($#array_name)。
print $#numbers_array;
# 4
print $numbers_array[$#numbers_array];
# 62
如果插入额外的美元符号,最后一个索引运算符($#array_name)也可以在数组引用上使用
my $arrayref = [41, 67, 13, 9, 62];
print $#$arrayref;
# 4
print $$arrayref[$#$arrayref];
# 62
负索引
Perl提供了一种更短的语法来访问数组的最后一个元素:负索引。负索引从数组的末尾开始跟踪,因此-1表示最后一个元素,-2表示倒数第二个元素,依此类推。
# Declare the array
my @cakes = qw(victoria_sponge chocolate_gateau carrot);
print $cakes[-1]; # carrot
print $cakes[-2]; # chocolate_gateau
print $cakes[-3]; # victoria_sponge
print $cakes[0]; # victoria_sponge
print $cakes[1]; # chocolate_gateau
print $cakes[2]; # carrot
本文最初发布在PerlTricks.com上。
标签
反馈
这篇文章有什么问题吗?请通过在GitHub上打开问题或拉取请求来帮助我们。