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

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.

5

 


grep

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".

2

 


while loop

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

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

 

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"

 


Math

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;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |