Text :: CSV analysis when data contains a new line

I have code that parses a csv file and also contains a new line. But Text :: CSV breaks when it encounters "\ n" inside the data

This is the parsing code.

use Data::Dumper; use Text::CSV; my $csv = Text::CSV->new ({ binary=> 1, eol => $/, allow_loose_quotes => 1, allow_loose_escapes=> 1 }) || die $!; #print Dumper($csv); my $file = $ARGV[0]; open my $csv_handle, $file or die $!; while (my $row = $csv->getline($csv_handle)) { print Dumper($row); } 

This is data

 196766,31,"MR SRINIVASALU LAKSHMIPATHY\"DEC\"\ \"71" 196766,56,"255233.47" 
+3
source share
1 answer

You also need to set escape_char to \ because it is equal to " by default. " However, this does not fix the problem if you run the version of pure-perl Text::CSV . With version XS ( Text::CSV_XS ) this works:

 use strict; use warnings; use Text::CSV; use Data::Dumper; my $csv = Text::CSV->new({ binary => 1, eol => "\n", quote_char => '"', escape_char => '\\', auto_diag => 2, allow_loose_escapes => 1, }) or die "Can't create CSV parser"; while( my $row = $csv->getline(\*DATA) ) { print Dumper $row; } __DATA__ 1,"2 ",3 196766,31,"MR SRINIVASALU LAKSHMIPATHY\"DEC\"\ \"71" 196766,56,"255233.47" 

The pure-Perl parser fails in the 2nd entry and complains about the missing closing quote. If we set allow_loose_quotes to true, then the CSV will figure it out, but the second record will be split (the third record is inserted with a single field containing \"71" ). Version XS does not show this behavior.

It looks like an error in the text :: CSV_PP.

+2
source

Source: https://habr.com/ru/post/1246003/


All Articles