How to parse a CSV with a newline and commas inside a field in Perl?

I am new to Perl. This is an example csv entry similar to mine. I would like to analyze this, tried briefly Text :: CSV, but no luck. Here we are talking about a new line and commas inside the fields. How can I parse this file in Perl? Thanks for the help.

1,A,"Length of x, where x is y" 2,B,"Set A to "10", an invalid state" 3,C,"Solve A+B and B+A " 4,D, Set C to B 
0
source share
2 answers

This code (taken directly from the Text :: CSV document):

 #!/usr/bin/perl use strict; use Text::CSV; use Data::Dumper; my $rows; my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attribute. or die "Cannot use CSV: ".Text::CSV->error_diag (); open my $fh, "<", "test.csv" or die "test.csv: $!"; while ( my $row = $csv->getline( $fh ) ) { push @{$rows}, $row; } $csv->eof or $csv->error_diag(); close $fh; # This gets rid of spaces at start and end of string # as well as newlines within the fields. for ( 0 .. scalar @{$rows}-1 ) { $rows->[$_][2] =~ s/^\s*//; $rows->[$_][2] =~ s/\n/ /gms; } print Dumper($rows); 

It produces the following output:

 $VAR1 = [ [ '1', 'A', 'Length of x, where x is y' ], [ '2', 'B', 'Set A to "10", an invalid state' ], [ '3', 'C', 'Solve A+B and B+A ' ], [ '4', 'D', 'Set C to B' ] ]; 

Which (I guess) is what you want to achieve.

+7
source

Thanks to everyone who commented on this, I understood. What I did not do was

 { binary => 1, eol => $/ } 

Here is the working code:

 #!/usr/bin/perl use 5.010; use strict; use warnings; use Text::CSV; open(my $Fh, "<", 'datalane_csr.csv'); my $csv = Text::CSV->new ({ binary => 1, eol => $/ }); while (my $row = $csv->getline ($Fh)) { say @$row[2]; } close(CSV); 

Thanks again. And sorry for the message.

But I have a little problem, "" appears as strange characters when I print them.

0
source

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


All Articles