如果我们有数组,那么我们可以做以下:
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".