Array Size in Perl

The size of an array in Perl can be determined using the scalar context on the array - the returned value will be the number of elements in the array −

@array = (1,2,3);
print "Size: ",scalar @array,"\n";

The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows −


 Live Demo

@array = (1,2,3);
$array[50] = 4;
$size = @array;
$max_index = $#array;

print "Size: $size\n";
print "Max Index: $max_index\n";


This will produce the following result −

Size: 51
Max Index: 50

There are only four elements in the array that contains information, but the array is 51 elements long, with the highest index of 50.

Updated on: 28-Nov-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started