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

Sac*_*hin 32 perl

如果我们有阵列,那么我们可以做以下事情:

my @arr = qw(Field3 Field1 Field2 Field5 Field4);
my $last_arr_index=$#arr;
Run Code Online (Sandbox Code Playgroud)

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

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

DVK*_*DVK 53

my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)];
my ($last_arr_index, $next_arr_index);
Run Code Online (Sandbox Code Playgroud)

如果您需要知道最后一个元素的实际索引,例如,您需要在知道索引的情况下遍历数组的元素,请使用$#$:

$last_arr_index = $#{ $arr_ref };
$last_arr_index = $#$arr_ref; # No need for {} for single identifier
Run Code Online (Sandbox Code Playgroud)

如果你需要知道最后一个元素的索引,(例如,填充下一个free元素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
Run Code Online (Sandbox Code Playgroud)

如果您真正需要的是访问 arrayref中的最后一个元素(例如,您希望知道索引的唯一原因是稍后使用该索引来访问该元素),您可以简单地使用"-1"索引引用的事实到数组的最后一个元素.Zaid的帖子为这个想法提供了道具.

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


fri*_*edo 16

my $last_aref_index = $#{ $arr_ref };
Run Code Online (Sandbox Code Playgroud)

  • 记得"接受"你认为最有帮助的答案. (7认同)

Zai*_*aid 7

您可能需要访问最后一个索引的原因是获取数组引用中的最后一个值.

如果是这种情况,您只需执行以下操作:

$arr_ref->[-1];
Run Code Online (Sandbox Code Playgroud)

->运营商取消引用.[-1]是数组的最后一个元素.

如果需要计算数组中的元素数量,则无需执行此操作$#{ $arr_ref } + 1.DVK已经展示了几种更好的方法.

  • 我们可能需要它我的$ hash_ref = {map {$ arr_ref - > [$ _] => $ _} 0 .. $#{$ arr_ref}}; (3认同)