bryan lobson
bryan lobson

Reputation: 29

count the occurrence of specific value in array

I want to count the occurrence of specific value in array, the array as below.

my @array = (-1.001, -7.032, -5.013, 8.412, -1.500, 3.412)

The expected result For value under zero count = 4

For value under minus 5 count = 2

How can I get it using Perl, Any Idea?

Upvotes: 1

Views: 3135

Answers (1)

mpapec
mpapec

Reputation: 50677

You can use grep to filter elements, and use it in scalar context when it returns number of list elements which passed the filter,

my $count1 = grep { $_ < 0  } @array;
my $count2 = grep { $_ < -5 } @array;

another way is to use foreach loop,

my $count1 = 0;
my $count2 = 0;
for (@array) {
  $count1++ if $_ < 0;
  $count2++ if $_ < -5;
}

Upvotes: 6

Related Questions