Вопрос

I have an array like @array=(1,2,3,4)

I also have a scalar, lets say 2. How do I check and see that there is one number less than 2, one number equal to 2, and 2 numbers greater than 2?

Это было полезно?

Решение

You can loop through each element and add to a counter, like this:

#!/usr/bin/perl
use strict;
use warnings;

my @array = qw/ 1 2 3 4/;

my $lower = 0;
my $equal = 0;
my $higher = 0;

for my $i (@array)
{
    if ($i < 2) { $lower += 1; }
    elsif ($i == 2) { $equal += 1; }
    else { $higher += 1; }
}
print "There are $lower elements lower than 2\n";
print "There are $equal elements equal to 2\n";
print "There are $higher elements higher than 2\n";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top