2010-06-04 353 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

相關問題