1

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?

1
  • Iterate over the array and count what you need. Commented Dec 18, 2014 at 9:15

1 Answer 1

7

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.