I have tried keep_meta_info =>1
But it is not working.
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $csv = Text::CSV->new({ sep_char => ',',
keep_meta_info =>1 });
my $file = $ARGV[0] or die "Need to get CSV file on the command line\n
+";
my $sum = 0;
open(my $data, '<', $file) or die "Could not open '$file' $!\n";
while (my $line = <$data>) {
chomp $line;
if ($csv->parse($line)) {
my @fields = $csv->fields();
print $fields[1],"\n";
} else {
warn "Line could not be parsed: $line\n";
}
}
Read the docs on that option: It keeps the metadata separately from the data, so to find out if a field was quoted, you need to look at the is_quoted method. Even though it's not a perfect solution, you could just tack the quotes back onto the field if is_quoted is true. (Perhaps another monk more versed in Text::CSV has a better solution.)
You are completely right, and there is no easier way to do it
use Text::CSV_XS;
my $csv = Text::CSV_XS->new ({
binary => 1,
auto_diag => 1,
keep_meta_info => 1,
});
my $file = $ARGV[0] or die "Need to get CSV file on the command line\n
+";
my $sum = 0;
open my $data, "<", $file or die "Could not open '$file' $!\n";
while (my $row = $csv->getline ($data)) {
foreach my $idx (0 .. $#row) {
$csv->is_quoted ($idx) or next;
$row->[$idx] =~ s/(.*)/"$1"/; # TIMTOWTDI
}
# @$row is now quoted as you want
}
close $data;