I may be missing something obvious, but I have a very simple perl script in which the is_quoted() method in the Text::CSV module is not working as expected. Here's the code:
# cat ./testcsv.pl
#!/usr/bin/perl
use strict;
use Text::CSV;
my $csv = Text::CSV->new ( { quote_char => '"' } )
or die "Cannot use CSV: ".Text::CSV->error_diag ();
print "Text::CSV version = " . $csv->version() . "\n\n";
my $line = '"text field 111",222,"text field 333",444';
my $status = $csv->parse($line);
if ($status)
{
my $column_idx = 0;
my @fields = $csv->fields ();
foreach my $field (@fields)
{
my $quoted = $csv->is_quoted ($column_idx);
$column_idx++;
print "field #$column_idx: '$field'; quoted = " . ($quoted ? "YES\n" : "NO\n");
}
}
And here's what I get when I run the script:
# perl -v | grep "is perl" This is perl, v5.10.1 (*) built for PA-RISC2.0 # ./testcsv.pl Text::CSV version = 1.29 field #1: 'text field 111'; quoted = NO field #2: '222'; quoted = NO field #3: 'text field 333'; quoted = NO field #4: '444'; quoted = NO #
As we can see, the parse() method is correctly separating the original string into fields, so I know that Text::CSV is installed and working correctly. It was my understanding from reading the documentation for Text::CSV that the is_quoted() method is supposed to return a true value if the data in the indicated column is enclosed in quote_char quotes. Therefore I was expecting to see 'YES' after fields 1 & 3, as they're clearly quoted in the initialization for the $line variable. But this is not happening.
Am I doing something wrong, or is Text::CSV broken?
To read a column from csv for this purpose I wrote this script: #!/usr/bin/perl -w use strict; use warnings; use Text::CSV; my$column_separator = qr/,/; my $column_number = "3"; my$file = "/home/Admin/Documents/new (copy).
A CSV file is a commonly used file extension when it comes to spreadsheets. Even software programs that don't look and feel like a spreadsheet application will frequently offer a CSV as an output file for downloading a data set, such as a report of results, actions, or contacts.
You need to specify keep_meta_info => 1
.
By the way, I dislike having two iterators, so I'd iterate over the indexes.
my @fields = $csv->fields();
for my $column_idx (0..$#fields) {
my $field = $fields[$column_idx];
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With