Skip to content
Related Articles

Related Articles

Perl | Getting the Number of Elements of an Array

View Discussion
Improve Article
Save Article
  • 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:

# Initializing the array
@a = (1, 2, 3);
# Assigning the array to a scalar
# variable which stores size of
# the array
$s = @a;
# Printing the size
print "Size of the Array is $s";


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:

# Initializing the array
@a = (1, 2, 3);
# Store the value at any index
# Let's take index 15 here,
$a[15] = 20;
# Printing the Array
print "Array is @a";
# Getting the maximum index 
# of the array
$i = $#a;
# Printing the Max. Index
print "\nMaximum index is $i";


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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!