Subject: | getline_hr_all dies silently when input field uses double-quotes |
Hi
Here is my output from running the attached 'text.csv.pl':
ron@zigzag:~$ perl text.csv.pl
Writing:
Input: <1One1>. Output: <1One1>
Input: <2"Two"2>. Output: <"2""Two""2">
Input: <3Three3>. Output: <3Three3>
Reading:
Line => 1One1.
ron@zigzag:~$
The " embedded and doubled in line 2 causes getline_hr_all to die
silently, so what the module writes can't be read.
Cheers
Ron
Subject: | text.csv.pl |
#!/usr/bin/env perl
use strict;
use warnings;
use IO::File;
use Text::CSV_XS;
use Try::Tiny;
# -----------------------------------------------
sub read_csv_file
{
my($file_name) = @_;
my($csv) = Text::CSV_XS -> new;
my($io) = IO::File -> new($file_name, 'r');
my($result);
try
{
$csv -> column_names($csv -> getline($io) );
$result = $csv -> getline_hr_all($io);
}
catch
{
die qq|Error: $_. err_diag: | . $csv -> err_diag;
};
return $result;
} # End of read_csv_file.
# -----------------------------------------------
sub write_csv_file
{
my($file_name, $data) = @_;
my($csv) = Text::CSV_XS -> new;
open(OUT, '>', $file_name) || die "Can't open(> $file_name): $!";
my($line);
my($status);
$status = $csv -> combine('Line') || die "Can't combine('Line'): " . $csv -> err_diag;
print OUT $csv -> string, "\n";
for my $row (@$data)
{
$status = $csv -> combine($row) || die "Can't combine($row): " . $csv -> err_diag;
$line = $csv -> string;
print OUT "$line. \n";
print "Input: <$row>. Output: <$line>\n";
}
close OUT;
} # End of write_csv_file.
# -----------------------------------------------
my($data) = ['1One1', '2"Two"2', '3Three3'];
my($file_name) = 'x.csv';
print "Writing: \n";
write_csv_file($file_name, $data);
print "Reading: \n";
my($result) = read_csv_file($file_name);
for my $row (@$result)
{
print join(', ', map{qq|$_ => $$row{$_}|} sort keys %$row), "\n";
}