如何从Perl脚本打印到CSV中的特定列

时间:2018-10-16 18:46:04

标签: perl csv

我有以下格式的CSV文件:

Config,name,sub,produce,negative,positive,dying
RDF-12,jakl,xol,12,4,2,4

在我的perl脚本中,我具有以下变量:

$config = 'LSF-13'
$produce = 34;
$positive = 6;
$dying = 3;

我缺少'name','sub'和'negative'列的变量,但仍想将我的变量放置(附加)在它们各自的列中。

$file = "/lsd/filepath/text.csv";
open $fh, '>>', $file or warn "can't open";
print $fh $config, $produce, $positive, $dying;

我的代码不允许我指定要与变量匹配的列。

所需的输出:

Config,name,sub,produce,negative,positive,dying
RDF-12,jakl,xol,12,4,2,4
LSF-13,,,34,,6,3

1 个答案:

答案 0 :(得分:2)

使用Text::CSV

use strict;
use warnings;
use utf8;
use Text::CSV;

my %row = (
  Config => 'LSF-13', # keys must match the case of the columns in your CSV exactly
  produce => 34,
  positive => 6,
  dying => 3,
);
my $file = "/lsd/filepath/text.csv";

# open to read the existing column names from the first line
open my $readfh, '<:encoding(UTF-8)', $file or die "can't open $file: $!";
my $csv = Text::CSV->new({eol => $/, binary => 1, auto_diag => 2});
$csv->column_names($csv->getline($readfh));
close $readfh;

# open to append a new line
open my $writefh, '>>:encoding(UTF-8)', $file or die "can't open $file: $!";
$csv->print_hr($writefh, \%row);