By Alvin Alexander. Last updated: June 4, 2016
A frequently asked question Perl question is "How do I determine the size/length of a Perl array?", or the equivalent "How do I determine how many elements are in a Perl array?"
There are at least three different ways to do determine the Perl array size/length. Here's some Perl source code that shows these three Perl array size approaches:
#----------------------------#
# create a simple Perl array #
#----------------------------#
@foods = qw(burgers fries shakes);
#-------------------------------------------------#
# three different ways to get the Perl array size #
#-------------------------------------------------#
# 1) perl array size with implicit scalar conversion:
$size1 = @foods;
# 2) perl array size with explicit scalar conversion:
$size2 = scalar @foods;
# 3) perl array size with using the index of the last
# element in the array, plus one:
$size3 = $#foods + 1;
# print the array sizes
printf("The sizes are %d, %d, and %d\n", $size1, $size2, $size3);
which has the corresponding output:
The sizes are 3, 3, and 3

