gpt4 book ai didi

perl - 使用 Text::CSV_XS 模块将列插入 Perl 中的 CSV 文件

转载 作者:行者123 更新时间:2023-12-05 02:23:34 26 4
gpt4 key购买 nike

如何使用 Text::CSV_XS 模块将列添加到 CSV 文件?

模块中的打印例程只将数组写成一行。如果我有一个数组,如何将它作为列写入文件?我已经写了下面的代码

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 文件返回指定的列。

最佳答案

要添加一列,只需向每一行添加一个元素并像往常一样打印这些行。以下将在您的 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 的元素少于行数,您将在输出中得到空格。

要在中间某处插入该列(例如,在第一列之后)而不是将其附加到末尾,请更改

push @$row, shift @column;

my $offset = 1; # zero-indexed
splice @$row, $offset, 0, shift @column;

输出:

foo,baz,bar
larry,moe,curly

关于perl - 使用 Text::CSV_XS 模块将列插入 Perl 中的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com