Bxr MKH
Bxr MKH

Reputation: 131

How to sum the values in if condition?

My output has the many values. But sum the particular values. My answer from the script like this

# $ans 
3.801
5.381
16.26
3.801
18.3
3.80
5.151
5.636
6.732
.
.
.

my $sum;
if($ans <= 8)
{ 
     $sum += $ans;
     print "$ans\n\n\n";

}
print "Total value below (8) : $sum";

How to sum the answer below 8 outside of the if condition? How can i do it?

Upvotes: 3

Views: 243

Answers (2)

Borodin
Borodin

Reputation: 126722

Another way that doesn't need a module.

use strict;
use warnings;

my $sum;
$_ < 8 and $sum += $_ while <DATA>;

print "Total value below (8): $sum\n";

__DATA__
3.801
5.381
16.26
3.801
18.3
3.80
5.151
5.636
6.732

output

Total value below (8): 34.302

Upvotes: 6

Miller
Miller

Reputation: 35198

Just use grep to filter out numbers you don't want from your list, and then use List::Util qw(sum)

use strict;
use warnings;

use List::Util qw(sum);

my $sum = sum grep {$_ < 8} <DATA>;

print $sum;

__DATA__
3.801
5.381
16.26
3.801
18.3
3.80
5.151
5.636
6.732

Outputs:

34.302

Upvotes: 5

Related Questions