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

为君一笑 提交于 2019-12-04 18:06:12

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!