The Perl Conference Salt Lake City 2018 Banner

Find the index of the last element in an array

Most Perl programmers know that to find the size of an array, the array must called in a scalar context like this:

# Declare the array
my @numbers_array = (41,67,13,9,62); 
# Get the array size
my $size_of_array = @numbers_array;

This understanding can lead to programmers applying a scalar context to an array to access its last element (subtracting 1 because arrays are zero-based).

print $numbers_array[@numbers_array - 1];
# 62

The last-index variable

Perl has a ‘last-index’ variable for arrays ($#array_name).

print $#numbers_array; 
# 4
print $numbers_array[$#numbers_array]; 
# 62

The last index operator ($#array_name) also works on arrayrefs if you insert an extra dollar sigil:

my $arrayref = [41, 67, 13, 9, 62];
print $#$arrayref;
# 4
print $$arrayref[$#$arrayref]; 
# 62

Negative indexing

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.

# Declare the array
my @cakes = qw(victoria_sponge chocolate_gateau carrot);
print $cakes[-1]; # carrot
print $cakes[-2]; # chocolate_gateau
print $cakes[-3]; # victoria_sponge
print $cakes[0];  # victoria_sponge
print $cakes[1];  # chocolate_gateau
print $cakes[2];  # carrot


This article was originally posted on PerlTricks.com.

Tags

David Farrell

David is the editor of Perl.com. An organizer of the New York Perl Meetup, he works for ZipRecruiter as a software developer.

Browse their articles

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub