2

I have a CSV file with a lot of columns and rows but I need to sum cells of certain column:

Samples | Name | Value1 | Value2 | Value3

A-Sample | A-Name | 1 | 32 | 27 | 21

B-Sample | B-Name | 2 | 23 | 12 | 13

C-Sample | C-Name | 3 | 10 | 98 | 59

D-Sample | D-Name | 4 | 21 | 78 | 72

E-Sample | E-Name | 5 | 32 | 72 | 27

I need Sum of cells in column Value 1, Sum of cells in column Value2. I'm trying to use Text::CSV, but I only get the result as lines.

Could anyone help me?

4

3 回答 3

0

对于这类事情,我最喜欢的模块是 Tie::Array::CSV

use Tie::Array::CSV;
tie my @csv, 'Tie::Array::CSV', 'filename.csv' or die;
my @answer;         # store the results
for (my $row = 1; $row < @csv; $row++) # each row if the csv
{
    next unless $row->[2] =~ /^\s*\d+\s*$/; # Not rows where 3rd field isn't numeric
    for (my $i = 2; $i < @$row; $i++)  # cols 2 onwards
    {
        $answer[$i] += $row->[$i];  # sum the results
    }
 }
 say "@answer[2 .. $#answer]"; # display the sums
于 2012-10-29T22:58:15.050 回答
0

I work with a lot of CSV files and my favorite modules by far are Tie::Handle::CSV and DBD::CSV.

perlmeme.org has a fantastic tutorial on parsing CSV files.

于 2012-11-02T23:40:38.080 回答
0

试试 Spreadsheet::Read,也许它适合您的需求。使用此模块,您可以像使用任何其他电子表格一样使用 csv。有关更多信息,请参阅 perldoc Spreadsheet::Read 或https://metacpan.org/module/Spreadsheet::Read

#! /usr/bin/env perl
use Modern::Perl '2012';

use Spreadsheet::Read;
use Data::Dumper;

my $spreadsheet = my $ref = ReadData ("test.csv", sep => "|"); 
my @rows = Spreadsheet::Read::rows ($spreadsheet->[1]);
my @values = map {$_->[4] } @rows; # columns starting with 0
say Dumper (\@values);

输出

$VAR1 = [
      'Value3',
      '27',
      '12',
      '98',
      '78',
      '72'
    ];
于 2012-10-26T18:20:34.817 回答