-1

I would like to read in a .csv file using CSV_XS then select columns from with by header to match what is stored in an array outputting a new .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);
        }

}
3
  • 1
    You don't need to create a new Text::CSV_XS object for each file. Apr 2, 2015 at 15:59
  • Also, can you clarify what you mean by "with headers matched in an array?" Are you saying that you only want to output the columns that match the values in a given array? Apr 2, 2015 at 16:01
  • Sorry not a perl expert by any means. updated the question @ThisSuitIsBlackNot Apr 2, 2015 at 16:38

2 Answers 2

1

The following example, just parse a CSV file to a variable, then you can match, remove, add lines to that variable, and write back the variable to the same CSV file.

In this example i just remove one entry line from the CSV. First, i would just parse the CSV file.

use Text::CSV_XS qw( csv );
$parsed_file_array_of_hashesv = csv(
    in      => "$input_csv_filename",
    sep     => ';',
    headers => "auto"
);    # as array of hash

Second, once you have the $parsed_file_array_of_hashesv, now you can loop that array in perl and detect the line you want to remove from the array. and then remove it using

splice ARRAY, OFFSET, LENGTH

removes anything from the OFFSET index through the index OFFSET+LENGT

lets assume index 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

Third, write back the array to the CSV file

$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"
); 

Notice, that if you use the \@sorted_column_names you will be able to control the order of the columns

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);
}

That should write the CSV file without your line.

1
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} ]);
   }
}
1
  • I'm not sure why you just unaccepted this and accepted the more complicated answer. There was a small bug which I've just fixed.
    – ikegami
    Feb 28, 2019 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.