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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 11:32:13

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/20863091/insert-column-to-a-csv-file-in-perl-using-textcsv-xs-module

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