Bootstrap FreeKB - Perl (Scripting) - Count elements in an array
Perl (Scripting) - Count elements in an array

Updated:   |  Perl (Scripting) articles

Let's say you have an array that contains 4 elements.

my @array = qw(orange apple peach grape pineapple);


In this example, the $count variable will contain the number of elements in @array.

my $count = @array;


You can print the $count variable;

print $count;


Which will return 5, meaning there are 5 elements in @array.




grep can be used to count the elements in an array that contain a string. In this example, grep is used to count the number of elements in @array that contain apple.

my $count = (grep(/apple/i, @array));


Which should return 2, since both apple and pineapple contain the string "apple".



while loop

This is often used in conjunction with a while loop to loop through each element in the array.

use strict;
use warnings;

my @array   = qw(value1 value2 value3 value4);
my $count   = @array;
my $integer = 0;

while ($integer lt $count) {
  print "Element $integer in \@array is $array[$integer] \n";


The following should be returned.

Element 0 in @array is "Orange"
Element 1 in @array is "Apple"
Element 2 in @array is "Peach"
Element 3 in @array is "Grape"



Additionsubtraction, division, and multiplication can be used to adjust the count, like this.

my $count = @array + 1;


Or like this.

my $count = @array;
$count = $count + 1;


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee


Add a Comment

Please enter 3ed113 in the box below so that we can be sure you are a human.