2012-03-29 38 views
0

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

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 
+6

显示。你试过的代码。它可能会工作Text :: CSV是一个好的模块 – Cfreak 2012-03-29 18:24:11

+0

最好的线索是......不要试图自己解析CSV。你为什么认为'Text :: CSV'不起作用? – dgw 2012-03-29 18:38:08

+0

对这篇文章感到抱歉,我想出了解决办法。我已经发布了它。 最初我试图解析自己,但后来看了Text :: CSV,但问题是由于我没有包括的选项。 对不起,谢谢。 – Vikyboss 2012-03-29 18:51:21

回答

7

此代码(直接从文本采取:: 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' 
      ] 
     ]; 

其中(我猜)是你想达到什么

+0

正是我想要的。这甚至会照顾到我的新行。非常感谢。 – Vikyboss 2012-03-29 18:55:27

+0

我的荣幸。很高兴能帮上忙。 – user1269651 2012-03-29 21:09:10

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); 

再次感谢。并为该帖子感到抱歉。

但我有一个小问题,“'显示为奇怪的字符,当我打印出来

相关问题