kumarkeyan has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a data (Refer below)

What, "girl,boy", are_you, "good , one"

I want to read the data and print the data with double quotes. I can able to read the data but double quotes are not printed in the output.
#!/usr/bin/perl use strict; use warnings; use Text::CSV; my $csv = Text::CSV->new({ sep_char => ',' }); my $file = $ARGV[0] or die "Need to get CSV file on the command line\n +"; 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"; } }
Please let me know how to print the data with double quotes.

Expected Output: "girl,boy"

Actual Output: girl,boy

Replies are listed 'Best First'.
Re: Escape Double Quotes
by toolic (Bishop) on Aug 07, 2014 at 13:09 UTC
      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.)
Re: Escape Double Quotes
by Anonymous Monk on Aug 07, 2014 at 15:30 UTC

    A comment unrelated to the question: Your code, while not wrong, will break if the CSV file contains data split over multiple lines (embedded newlines). Because of this, the recommended way to read a CSV file is with the getline method of Text::CSV (there's an example in the Synopsis). Also, it's usually a good idea to turn on the binary option.

Re: Escape Double Quotes
by Anonymous Monk on Aug 07, 2014 at 13:10 UTC
    Maybe the is_quoted method in combination with the keep_meta_info option can help you?