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".
來源
2010-06-04 16:07:51
DVK
謝謝DVK。這正是我在回答我的答案時所想的。 – Zaid 2010-06-04 16:38:02