使用标题行解析CSV文件

时间:2018-01-22 20:17:23

标签: perl csv

我有一个带有标题行的CSV文件,我需要使用Perl来解析我所处的环境。

传入的CSV文件具有以下格式(每行分隔数据的标题):

Short_Description,Priority,Status,Office_Location,E-mail,Contact_Type,Service_Level,Campus,Ticket_Priority,Region,Country,School,First_Seen,Detection_Method,Description,Assignees 
Patch system,Important,Pending,Maryland,test@email.com,Contractor,Standard,Annapolis,Req-Routine,N/A,N/A,N/A,1/12/2018,Others,TestofDescription,TestAssignee

到目前为止,我有这段代码:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

use Text::CSV_XS;
use Data::Dumper;

my $file = $ARGV[0] or die "Need to get CSV file";

my @rows; # array that will store csv values


my $csv = Text::CSV_XS->new ( { binary => 1 } ) or die "Cannot use CSV: ".Text::CSV->error_diag ();

# open file
open my $FH, "<:encoding(utf8)", "$file" or die "$file: $!";

# Skip Header row
<$FH> for 0;

# read file in while loop

while ( my $row = $csv->getline( $FH ) ) {        
    {
        push @rows, $row;
    }
}

$csv->eof or $csv->error_diag();

# close file
close $FH;

返回:

     Patch system Important Pending Maryland test@email.com Contractor Standard Annapolis Req-Routine N/A N/A N/A 1/12/2018 Others TestofDescription TestAssignee

完成此操作后,每个数组元素都是包含数据的行。我正处于需要解析变量条目中的数据的地步,但我无法掌握执行此操作所需的上下文/语法。由于字段将包含字符串条目,我需要以不被视为新条目的方式解析数据。 &#34;补丁系统&#34;作为一个例子,需要保持在一起。

1 个答案:

答案 0 :(得分:1)

我认为你要求

my($ short_desc,$ priority,$ status,...)= @ $ row;

但这对字段的顺序做出了不必要的假设。

use Text::CSV_XS qw( );

@ARGV == 1
    or die("usage\n");

my ($qfn) = @ARGV;

open(my $FH, "<:encoding(utf8)", $qfn)
    or die("Can't open input file \"$qfn\": $!\n");

my $csv = Text::CSV_XS->new({ auto_diag => 2, binary => 1 });

$csv->header($fh);    

while ( my $row = $csv->getline_hr($FH) ) {
    my (
        $short_desc,
        $priority,
        $status,
        ...
    ) = @$row{qw(
        Short_Description
        Priority
        Status
        ...
    )};

    ...
}
相关问题