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