Perl -- Size of an Array

To find the size of an array in Perl, simply use the array in a scalar context.

my @items = ("apple", "orange", "banana");

my $size = @items;

print "Array contains $size items.\n";






Array contains 3 items.




Here we're using the array as if it was a single number; Perl is clever enough to give you the number of elements in the array when you do this.

Since the above usage can be confusing to non Perl experts, you can always use the scalar keyword to make things more explicit:

my @items = ("apple", "orange", "banana");

my $size = scalar(@items);

print "Array contains $size items.\n";




Array contains 3 items.




If for some reason you want to know the index of the last element in an array, there's a quick way of getting it:

my @items = ("mercury", "venus", "earth", "mars");

print $#items, "\n";
print $items[$#items], "\n";




3
mars