Perl如何获取数组引用的最后一个元素的索引?

如果我们有数组,那么我们可以做以下:
my @arr = qw(Field3 Field1 Field2 Field5 Field4);
my $last_arr_index=$#arr;

我们如何做这个数组引用?

my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)];
my $last_aref_index; # how do we do something similar to $#arr;

解决方法

my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)];
my ($last_arr_index,$next_arr_index);

如果你需要知道最后一个元素的实际索引,例如你需要循环遍历数组的元素知道索引,使用$#$:

$last_arr_index = $#{ $arr_ref };
$last_arr_index = $#$arr_ref; # No need for {} for single identifier

如果你需要知道最后一个元素之后的索引,(例如,没有push()填充下一个自由元素)

或者你需要知道数组中元素的数量(这是相同的数字)如上:

my $next_arr_index = scalar(@$arr_ref);
$last_arr_index = $next_arr_index - 1; # in case you ALSO need $last_arr_index
# You can also bypass $next_arr_index and use scalar,# but that's less efficient than $#$ due to needing to do "-1"
$last_arr_index = @{ $arr_ref } - 1; # or just "@$arr_ref - 1"
   # scalar() is not needed because "-" operator imposes scalar context 
   # but I personally find using "scalar" a bit more readable
   # Like before,{} around expression is not needed for single identifier

如果你真正需要的是访问arrayref中的最后一个元素(例如,您希望知道索引是后来使用该索引访问元素的唯一原因),你可以简单地使用“-1”索引到数组的最后一个元素。赞助Zaid的帖子的想法。

$arr_ref->[-1] = 11;
print "Last Value : $arr_ref->[-1] \n";
# BTW,this works for any negative offset,not just "-1".

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...