Perl array length (size)

Perl array length FAQ: "How can I determine the length of a Perl array?"

Answer: There are several different ways to determine the Perl array length.

Perl array length - Version 1

The first way to determine the Perl array length is by simple assigning a scalar variable to the array, like this:

$length = @foods;

The variable $length will now hold the length of the Perl array. This is referred to as "implicit scalar conversion", and it is probably the easiest and most common way to determine the Perl array length. However, there are at least two other approaches to determing the array length, and I'll show them here in case you run into them.

Perl array length - Version 2

The second way to determine the Perl array length is with "explicit scalar conversion", like this:

$length = scalar @foods;

This is just a slightly-more obvious array length approach to what I showed in the first example.

Perl array length - Version 3

In the third approach, if you have an array named @pizzas, the last element of the array can be addressed like this:

$pizzas[$#pizzas]

and the Perl array length is given by:

$#pizzas + 1

For some reason I used to use this approach, but as you can see, the first two approaches to determining the Perl array length are much easier to use and remember.

Given all that information, I'll leave you with this short but complete example that shows how to determine the length of an array in Perl:

@foods = qw(burgers fries shakes);
$length = @foods;
print $length, "\n";