要添加列,只需向每行添加一个元素并像平常一样打印行即可。以下内容将在 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
请注意,如果@column
元素少于行数,您将在输出中得到空格。
要将列插入到中间的某个位置(例如,在第一列之后)而不是将其附加到末尾,请更改
push @$row, shift @column;
to
my $offset = 1; # zero-indexed
splice @$row, $offset, 0, shift @column;
Output:
foo,baz,bar
larry,moe,curly