Как напечатать на конкретный столбец в CSV из Perl-скрипта - PullRequest
0 голосов
/ 16 октября 2018

У меня есть 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;

Мне не хватает переменных для имени столбца',' sub 'и' absolute ', но я все еще хочу поместить (добавить) мои переменные в соответствующие столбцы.

$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 голосов
/ 16 октября 2018

Использование Текст :: 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...