Perl | Getting the Number of Elements of an Array
Last Updated :
18 Feb, 2019
An array in Perl is a variable used to store an ordered list of scalar values. An array variable is preceded by an “at” (@) sign. The size of an array can be determined using the scalar context on the array which returns the number of elements in the array
Example 1:
@a = (1, 2, 3);
$s = @a ;
print "Size of the Array is $s" ;
|
Output:
Size of the Array is 3
Above code returns the physical size of the array, not the number of valid elements. In order to obtain the maximum index of an array, ‘$#’ is used as shown in the example below:
Example 2:
@a = (1, 2, 3);
$a [15] = 20;
print "Array is @a" ;
$i = $#a ;
print "\nMaximum index is $i" ;
|
Output:
Array is 1 2 3 20
Maximum index is 15
Here is how the above code works:-
Step1: Initializing an array with some values
Step2: Assigning a value at any random index leaving the other indices blank
Step3: Printing the array to show the blank spaces left in the array
Step4: To get the maximum index ‘$#’ is used
Step5: Further, print the maximum index
Share your thoughts in the comments
Please Login to comment...