Perl 如何获取数组引用的最后一个元素的索引? [英] Perl How to get the index of last element of array reference?

查看:179
本文介绍了Perl 如何获取数组引用的最后一个元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有数组,那么我们可以执行以下操作:

If we have array then we can do following:

my @arr = qw(Field3 Field1 Field2 Field5 Field4);
my $last_arr_index=$#arr;

我们如何为数组引用执行此操作?

How do we do this for array reference?

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);

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

If you need to know the actual index of last element, for example you need to loop over the array's elements knowing the index, use $#$:

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

如果您需要知道最后一个元素的索引,(例如,在没有 push() 的情况下填充下一个空闲元素),

If you need to know the index of element after the last, (e.g. to populate next free element without push()),

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

OR you need to know the amount of elements in the array (which is the same number) as above:

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 的帖子提出这个想法.

If what you actually need is to access the last element in the arrayref (e.g. the only reason you wish to know the index is to later use that index to access the element), you can simply use the fact that "-1" index refers to the last element of the array. Props to Zaid's post for the idea.

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

这篇关于Perl 如何获取数组引用的最后一个元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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