使用 CSV_XS 读入 .CSV 文件和 select 指定列

Use CSV_XS to read in a .CSV file and select specified columns

我想使用 CSV_XS 读取 .csv 文件,然后使用 header 中的 select 列来匹配数组中存储的内容,输出新的 .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);
        }

}
use open ":std", ":encoding(UTF-8)";

use Text::CSV_XS qw( );

# Name of columns to copy to new file.
my @col_names_out = qw( ... );

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

for (...) {
   my $qfn_in  = ...;
   my $qfn_out = ...;

   open(my $fh_in, "<", $qfn_in)
      or die("Can't open \"$qfn_in\": $!\n");
   open(my $fh_out, "<", $qfn_out)
      or die("Can't create \"$qfn_out\": $!\n");

   $csv->column_names(@{ $csv->getline($fh_in) });
   $csv->say($fh_out, \@col_names_out);

   while (my $row = $csv->getline_hr($fh_in)) {
      $csv->say($fh_out, [ @$row{@col_names_out} ]);
   }
}

下面的例子,只是将一个CSV文件解析为一个变量,然后你可以匹配,删除,添加行到那个变量,并将变量写回同一个CSV文件。

在这个例子中,我只是从 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

其次,一旦你有了 $parsed_file_array_of_hashesv,现在你可以在 perl 中循环那个数组并检测你想从数组中删除的行。 然后使用

删除它

拼接阵列、偏移量、长度

通过索引 OFFSET+LENGT

从 OFFSET 索引中删除任何内容

假设索引为 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_names,您将能够控制列的顺序

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 文件。