Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

- METHOD 1

Use the array in scalar context to get the size (number of elements) of the array. To force an array to be evaluated in scalar context, use the scalar operator.

Example:
print "Size of array is " . scalar @array;

IMPORTANT! Please notice that this method ONLY works with arrays, it doesn't work with lists; if you evaluate a list in scalar context it will return the value of the last element of the list (like in the C language)

Example:

#-- WRONG! $size will have 'perl' instead of '3'
$size = ( "c", "python", "ruby", "perl" );
print "Size of array is $size\n";

- METHOD 2

Another option is to use the value '$#array' which holds the value of the last subscript of '@array'; as subscripts range from 0 to (array length - 1) then the length of an array named '@array' is '$#array'.

Example:
printf "Size of arra is %d\n", $#array + 1;