每當我與CSV工作,我用的是AnyData
模塊。它可能會增加一些開銷,但它使我不會犯錯誤(「哦,廢話,那個日期欄被引用,並且有逗號!?」)。
你會看起來像這樣的過程:
use AnyData;
my @columns = qw/date type1 type2 type3/; ## Define your input columns.
my $input = adTie('CSV', 'input_file.csv', 'r', {col_names => join(',', @columns)});
push @columns, 'total'; ## Add the total columns.
my $output = adTie('CSV', 'output_file.csv', 'o', {col_names => join(',', @columns)});
my %totals;
while (my $row = each %$input) {
next if ($. == 1); ## Skip the header row. AnyData will add it to the output.
my $sum = 0;
foreach my $col (@columns[1..3]) {
$totals{$col} += $row->{$col};
$sum += $row->{$col};
}
$totals{total} += $sum;
$row->{total} = $sum;
$output->{$row->{date}} = $row;
}
$output->{Total} = \%totals;
print adDump($output); ## Prints a little table to see the data. Not required.
undef $input; ## Close the file.
undef $output;
輸入:
date,type1,type2,type3
2009-07-01,1,2,3
2009-07-03,31,32,33
2009-07-06,61,62,63
"Dec 31, 1969",81,82,83
輸出:
date,type1,type2,type3,total
2009-07-01,1,2,3,6
2009-07-03,31,32,33,96
2009-07-06,61,62,63,186
"Dec 31, 1969",81,82,83,246
Total,174,178,182,534
謝謝,這工作,但直到0變得可以計算值。你能否建議如何添加0值的字段。 – Space 2009-11-16 14:27:12
糟糕,修正了 – rsp 2009-11-16 15:43:38
請勿使用'chop',請使用'chomp'。 – 2009-11-17 01:28:50