Rate this page

Get the size of an array in Perl

Tested on

Debian (Etch, Lenny, Squeeze)
Fedora (14)
Ubuntu (Hardy, Intrepid, Jaunty, Karmic, Lucid, Maverick, Natty, Precise, Trusty)


To obtain the size of an array in Perl.


Evaluate the array in a scalar context. This could be an implicitly scalar context:

my $size = @array;

or one made explicit using the scalar function:

my $size = scalar @array;

The latter form is necessary in what would otherwise be an implicit array context, for example:

my @sizes = (scalar @array1,scalar @array2);

Without scalar this would have the effect of concatenating the two arrays instead of returning their sizes.

Even if it is not strictly needed, the use of scalar may be desirable for the purpose of improving readability.


An alternative method you may encounter is to take the index of the final element then add one:

my $size = $#array + 1;

Tags: perl