Perl | Getting the Number of Elements of an Array

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# 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";

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# 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";

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.