如何在Perl中的字段内使用换行符和逗号解析CSV?

Vik*_*oss 0 csv perl

我是Perl的新手.这是一个类似于我的示例csv条目.我想解析一下,试一试Text :: CSV,但没有运气.这里的问题是字段内的换行符和逗号.我怎么能在Perl中解析这个文件?谢谢您的帮助.

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
Run Code Online (Sandbox Code Playgroud)

小智 7

此代码(直接取自Text :: CSV文档):

#!/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);
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

$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'
          ]
        ];
Run Code Online (Sandbox Code Playgroud)

哪(我猜)是你想要实现的.