如何读取CSV并跟踪某些值的更改

时间:2019-04-12 23:02:46

标签: perl csv

我有一个CSV文件:

Name,Week,Planned,Passed
AST,01,5,8
KST,01,9,14
RST,01,76,23
AST,02,12,45
KST,02,5,4
RST,02,13,65
GST,02,76,12
LST,03,12,43
AST,04,54,34

我正在从此文件读取数据,并根据CSV中的信息使用Perl填充HTML文件:

while (!eof(FH)) { //while csv file is opened


my $line = <FH>;

chomp $line;

my($name,$week,$planned,$passed) = split(",", $line);

$currentHash{$name}{"week"} = $week;
$currentHash{$name}{"week"} = $planned;
$currentHash{$name}{"week"} = $passed;

$datafile = area/${week}/test.html

open my $fh, ">", $datafile;

if ($week != "Week") {

push @weekArray, qq( <td aligh=center bgcolor=#FFFFF font size='2'>$name</td>\n);

push @weekArray, qq( <td aligh=center bgcolor=#FFFFF font size='2'>$week</td>\n);

push @weekArray, qq( <td aligh=center bgcolor=#FFFFF font size='2'>$planned</td>\n);

push @weekArray, qq( <td aligh=center bgcolor=#FFFFF font size='2'>$passed</td>\n);


} //end of if

print $fh @weekArray;
close $fh

} //end of while

此代码成功创建带有CSV文件信息的表。但是,它不会创建在新week之后创建换行符的表。

我很难弄清楚如何检测新一周的开始时间,因为这一切都在循环之中。

当我阅读文件时,我想在每周数字更改时都放置一个换行符。我还需要在特定星期内不进行硬编码,因为星期数是任意的。

我希望表格看起来如何:

Name,Week,Planned,Passed
AST,01,5,8
KST,01,9,14
RST,01,76,23

AST,02,12,45
KST,02,5,4
RST,02,13,65
GST,02,76,12

LST,03,12,43

AST,04,54,34

1 个答案:

答案 0 :(得分:2)

只需记住上一个范围更广的变量遇到的最后一周。使用Text::CSV_XS处理CSV文件。

#!/usr/bin/perl
use warnings;
use strict;

use Text::CSV_XS;

my $week = 'Week';
my $csv = 'Text::CSV_XS'->new({binary => 1, auto_diag => 1});
open my $fh, "<", shift or die $!;
while (my $row = $csv->getline($fh)) {
    print "\n" if $week ne $row->[1];
    $week = $row->[1];
    $csv->say(*STDOUT, $row);
}