Tuesday, 11 March 2014

FINDING SIZE OF ARRAY



Array Size

The size of an array can be determined using 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 as follows:
#! /uer/bin/perl
 
@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 following result:
Size: 51
Max Index: 50
There are only four elements in the array that contain information, but the array is 51 elements long, with a highest index of 50.

No comments: