perl

How can I sum up the data in a comma and newline separated CSV file using a while loop and split?


The Perl script has to load in a CSV data file and sum up all the numbers in the file. There are only numbers in the file separated by commas and newlines. I have the bulk of the code done, but I am not getting the correct total. I might be overlooking something or have a fundamental misunderstanding of a concept or two, and any help would be greatly appreciated.

Example CSV data to be all summed up:

2, 6, 7, 10, 12
15, 22, 13
11, 4
1

The sum should be 103.

I have to use while(<>) and split to read in the data, and the code must be at a level that a newbie could produce, so please no advanced code unless absolutely necessary.

Here is my code:

use strict;
use warnings;

while (<>) {
        chomp;
        my $total = 0;
        my @array1 = split(',');
        foreach my $i (@array1){
        $total +=  $i;

        }
print $total;
}

The $total variable ends up containing the sums of each row of the array as one number, and I am struggling to figure out how I can rewrite this to make it do what I want it to. Any help is greatly appreciated. Also, if the supplied code could be aimed at a newb (similar to what I have provided), that would be great.


Solution

  • Move the initialization of the total before the loop, and move the print after the loop:

    use strict;
    use warnings;
    
    my $total = 0;
    while (<DATA>) {
        chomp;
        my @array1 = split(',');
        foreach my $i (@array1) {
            $total +=  $i;
        }
    }
    print $total;
    print "\n";
    
    __DATA__
    2, 6, 7, 10, 12
    15, 22, 13
    11, 4
    1
    

    Your code resets the total after each line of your input.