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