0

I have a CSV file in the following format:

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

In my perl script, I have following variables:

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

I am missing variables for the columns 'name', 'sub', and 'negative' but still want to place(append) my variables in their respective columns.

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

My code is not allowing me to specify the columns I want to match with my variable however.

Desired Output:

Config,name,sub,produce,negative,positive,dying
RDF-12,jakl,xol,12,4,2,4
LSF-13,,,34,,6,3
4
  • Can you just add blank values using undef for the fields that are missing? $config, undef, undef, $produce, undef, $positive, $dying Commented Oct 16, 2018 at 18:48
  • What is your desired output? (How does LSF-13 get "appended" to the Config field ... like RDF-12 LSF-13 ...? Commented Oct 16, 2018 at 18:50
  • @zdim Edited a desired output section Commented Oct 16, 2018 at 18:55
  • Well say $fh $config, ',', ',', $produce ... (etc). But, isn't there more to it? What if you have more lines to add, how do you designate variables (hash with column names?) Commented Oct 16, 2018 at 19:00

1 Answer 1

2

Using 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.