Search code examples
perlcsvperl-moduleexport-to-csv

Insert column to a CSV file in Perl using Text::CSV_XS module


How can I add column to a CSV file using the Text::CSV_XS module?

The print routine in the module only writes the array as a row. If I have an array, how can I write it to the file as a column? I already wrote the code below

open my $outFH, ">", $outFile or die "$outFile: $!";
$outFilecsv = Text::CSV_XS->new ({ binary => 1, eol => $/ });              
@column = read_column($inFile, $i);
$outFilecsv->print($outFH, \@column)or $outFilecsv->error_diag;

where read_column method reads returns a specified column from another csv file.


Solution

  • To add a column, simply add a single element to each row and print the rows as you normally would. The following will append a column to the end of your CSV:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Text::CSV_XS;
    
    my @column = qw(baz moe);
    
    my $csv = Text::CSV_XS->new({ binary => 1, auto_diag => 1, eol => $/ });
    
    open my $in, "<", "in.csv" or die $!;
    open my $out, ">", "out.csv" or die $!;
    
    while (my $row = $csv->getline($in)) {
        push @$row, shift @column;
        $csv->print($out, $row);
    }
    
    close $in;
    close $out;
    
    rename "out.csv", "in.csv" or die $!;
    

    Input:

    foo,bar        
    larry,curly
    

    Output:

    foo,bar,baz
    larry,curly,moe
    

    Note that if @column has fewer elements than there are rows, you will get blank spaces in the output.

    To insert the column somewhere in the middle (say, after the first column) instead of appending it to the end, change

    push @$row, shift @column;
    

    to

    my $offset = 1; # zero-indexed
    splice @$row, $offset, 0, shift @column;
    

    Output:

    foo,baz,bar
    larry,moe,curly