6

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?

4

1 に答える 1

7

を指定する必要がありますkeep_meta_info => 1


ところで、イテレータが 2 つあるのは嫌いなので、インデックスを反復処理します。

my @fields = $csv->fields();
for my $column_idx (0..$#fields) {
   my $field = $fields[$column_idx];
   ...
}
于 2013-01-07T22:25:42.623 に答える