If we have array then we can do following:
my @arr = qw(Field3 Field1 Field2 Field5 Field4); my $last_arr_index=$#arr;
How do we do this for array reference?
my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)]; my $last_aref_index; # how do we do something similar to $#arr;
Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.
Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed. The reason we are subtracting 1 from the length is, in JavaScript, the array index numbering starts with 0. i.e. 1st element's index would 0.
Perl returns element referred to by a negative index from the end of the array. For example, $days[-1] returns the last element of the array @days .
my $arr_ref = [qw(Field3 Field1 Field2 Field5 Field4)]; my ($last_arr_index, $next_arr_index);
If you need to know the actual index of last element, for example you need to loop over the array's elements knowing the index, use $#$
:
$last_arr_index = $#{ $arr_ref }; $last_arr_index = $#$arr_ref; # No need for {} for single identifier
If you need to know the index of element after the last, (e.g. to populate next free element without push()
),
OR you need to know the amount of elements in the array (which is the same number) as above:
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
If what you actually need is to access the last element in the arrayref (e.g. the only reason you wish to know the index is to later use that index to access the element), you can simply use the fact that "-1" index refers to the last element of the array. Props to Zaid's post for the idea.
$arr_ref->[-1] = 11; print "Last Value : $arr_ref->[-1] \n"; # BTW, this works for any negative offset, not just "-1".
my $last_aref_index = $#{ $arr_ref };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With