使用Text :: CSV_XS模块将列插入Perl中的CSV文件 [英] Insert column to a CSV file in Perl using Text::CSV_XS module
问题描述
如何使用Text :: CSV_XS模块将列添加到CSV文件?
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;
其中read_column方法读取的位置会从另一个csv文件返回指定的列.
where read_column method reads returns a specified column from another csv file.
推荐答案
要添加一列,只需在每行中添加一个元素,然后照常打印即可.以下内容将在CSV末尾添加一列:
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 $!;
输入:
foo,bar
larry,curly
输出:
foo,bar,baz
larry,curly,moe
请注意,如果@column
的元素数少于行数,则输出中将出现空格.
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;
到
my $offset = 1; # zero-indexed
splice @$row, $offset, 0, shift @column;
输出:
foo,baz,bar
larry,moe,curly
这篇关于使用Text :: CSV_XS模块将列插入Perl中的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!