2010-06-04 127 views
28

如果我们有数组,那么我们可以做到以下几点: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; 

回答

49
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 

如果实际需要的是访问的最后一个元素在数组引用(例如只有原因你希望知道索引是为了以后使用该索引来访问元素),你可以简单地使用“-1”索引引用数组的最后一个元素的事实。道具Zaid的这个想法的职位。

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

谢谢DVK。这正是我在回答我的答案时所想的。 – Zaid 2010-06-04 16:38:02

12
my $last_aref_index = $#{ $arr_ref }; 
+0

谢谢friedo。这是我正在寻找的。 – Sachin 2010-06-04 16:15:53

+6

请记住“接受”你认为最有帮助的答案。 – 2010-06-04 16:24:18

5

你可能需要访问的最后一个索引的原因是为了获得在数组引用的最后一个值。

如果是这样的话,你可以简单地做到以下几点:

$arr_ref->[-1]; 

->操作指针引用。 [-1]是数组的最后一个元素。

如果您需要计算阵列中元素的数量,则不需要执行$#{ $arr_ref } + 1。 DVK已经显示a couple of better ways来做到这一点。

+0

但是,这给你最后一个元素的价值,而不是它的指数。 – friedo 2010-06-04 16:13:23

+0

是的,但为什么其他人想要最后的索引?我已经相应地确定了我的答案。 – Zaid 2010-06-04 16:26:12

+2

我们可能会要求它 my $ hash_ref = {map {$ arr_ref - > [$ _] => $ _} 0 .. $#{$ arr_ref}}; – Sachin 2010-06-04 16:37:40

0
my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)]; 

my $last_aref_index = $$arr_ref[$#{$arr_ref}]; 
print "last element is: $last_aref_index\n"; 
+0

在未来,您可能想要使用代码格式(由4个空格标识或单击编辑器中的“代码”按钮) – DVK 2010-06-04 16:20:13

+0

谢谢。我可能也想更仔细地阅读这个问题,因为我的例子返回的是“Field4”,而不是索引#... jw – jason 2010-06-04 16:22:44

相关问题