简体   繁体   中英

Adding or summing up numbers in each row in Perl

I want to add numbers in each row. For example my row have following no,

@lines = ("1 .2 .3 .4 .5","2  .7 .8 .8  .10 ","  3 .12 .13  .14 .15");

I want to add numbers each row separately. The first digit (1, 2 and 3) in each line is the row number, which I do not want to include in summation.

I tried :

($total+=$_) for @temp[1..$#temp];
print "The row adds up to $total";

It gave me total for last row ie 3rd row =.54

Please suggest me how to fix this.

Thank you

Simply split each string on whitespace (the default for split ) and use splice to extract all but the first element. Using map produces one long list of numbers to be added. The code looks like this

use strict;
use warnings;

my @lines = ("1 .2 .3 .4 .5", "2  .7 .8 .8  .10 ", "  3 .12 .13  .14 .15");

my $total;
$total += $_ for map { my @f = split; splice @f, 1; } @lines;

print $total;

output

4.34

EDIT

My apologies - I have only just noticed that you want the total for each string separately. Here is my solution for that

use strict;
use warnings;

my @lines = ("1 .2 .3 .4 .5","2  .7 .8 .8  .10 ","  3 .12 .13  .14 .15");

print "$_\n" for map {
  my @f = split;
  my $total;
  $total += $_ for splice @f, 1;
  $total;
} @lines;

output

1.4
2.4
0.54

Actually 0.54 is the correct sum for the 3rd row imho. Here a code snippet that computes the sum for all 3 rows.

@lines = ("1 .2 .3 .4 .5","2  .7 .8 .8  .10 ","  3 .12 .13  .14 .15");

foreach (@lines) {
        @row=split;

        $total=0;
        $total+=$_ for @row[1..$#row];

        print "Result $row[0]: $total\n";
}

Output:

Result 1: 1.4
Result 2: 2.4
Result 3: 0.54

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM