Perl 使用CSV_XS读取.CSV文件并选择指定的列

Perl 使用CSV_XS读取.CSV文件并选择指定的列,perl,csv,export,Perl,Csv,Export,我想使用CSVxs读入一个.csv文件,然后从按标题选择列,以匹配输出新.csv的数组中存储的内容 use strict; use warnings; use Text::CSV_XS; my $csvparser = Text::CSV_XS->new () or die "".Text::CSV_XS->error_diag(); my $file; my @headers; foreach $file (@args){ my @CSVFILE;

我想使用CSVxs读入一个.csv文件,然后从按标题选择列,以匹配输出新.csv的数组中存储的内容

use strict;
use warnings;




use Text::CSV_XS;

my $csvparser = Text::CSV_XS->new () or die "".Text::CSV_XS->error_diag();
my $file;
my @headers;

foreach $file (@args){
        my @CSVFILE;
        my $csvparser = Text::CSV_XS->new () or die "".Text::CSV_XS->error_diag();


        for my $line (@csvfileIN) {
                $csvparser->parse($line);
                my @fields = $csvparser->fields;

                $line = $csvparser->combine(@fields);
        }

}

在下面的示例中,只需将一个CSV文件解析为一个变量,然后就可以对该变量进行匹配、删除、添加行,并将该变量写回同一个CSV文件

use Text::CSV_XS qw( csv );
$parsed_file_array_of_hashesv = csv(
    in      => "$input_csv_filename",
    sep     => ';',
    headers => "auto"
);    # as array of hash
在这个例子中,我只是从CSV中删除了一个条目行。 首先,我将只解析CSV文件

use Text::CSV_XS qw( csv );
$parsed_file_array_of_hashesv = csv(
    in      => "$input_csv_filename",
    sep     => ';',
    headers => "auto"
);    # as array of hash
第二,一旦获得了\u hashesv的$parsed\u file\u array\u,现在就可以在perl中循环该数组,并检测要从数组中删除的行。 然后使用

拼接阵列、偏移、长度

通过索引偏移+长度从偏移索引中删除任何内容

让我们假设索引为0

my @extracted_array = @$parsed_file_array_of_hashesv;    #dereference hashes reference
splice @extracted_array, 0, 1;#remove entry 0
$ref_removed_line_parsed = \@extracted_array;            #referece to array
第三,将数组写回CSV文件

$current_metric_file    = csv(
    in      => $ref_removed_line_parsed,                 #only accepts referece
    out     => "$output_csv_filename",
    sep     => ';',
    eol     => "\n",                                   # \r, \n, or \r\n or undef
    #headers => \@sorted_column_names,              #only accepts referece
    headers => "auto"
); 
请注意,如果使用\@sorted_column_名称,则可以控制列的顺序

my @sorted_column_names;
foreach my $name (sort {lc $a cmp lc $b} keys %{ $parsed_file_array_of_hashesv->[0] }) { #all hashes have the same column names so we choose the first one
    push(@sorted_column_names,$name);
}

这将写入CSV文件而不使用您的行。

您不需要为每个文件创建一个新的Text::CSV_XS对象。另外,您能否澄清在数组中匹配标题的含义?您是说您只想输出与给定数组中的值相匹配的列吗?对不起,我不是perl专家。更新了问题@ThisSuitesBlackNot我不知道你为什么不接受这个,而接受了更复杂的答案。我刚刚修复了一个小错误。