Perl array length FAQ: "How can I determine the length of a Perl array?"
Solution
There are several different ways to determine the Perl array length, and I show those here.
Solution 1: Perl array length
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 determining the array length, and I'll show them here in case you run into them.
Solution 2: Perl array length
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.
Solution 3: Perl array length
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.
Example
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";