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

时间:2012-03-29 18:21:25

标签: perl csv

我是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

2 个答案:

答案 0 :(得分: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);

产生以下输出:

$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'
          ]
        ];

(我猜)是你想要达到的目标。

答案 1 :(得分:0)

谢谢所有评论的人,我明白了。我没做的事是

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

以下是工作代码:

#!/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);

再次感谢。抱歉这个帖子。

但我有一个小问题,'''在我打印时显示为奇怪的字符。

相关问题