如何在Perl的字段中使用换行符和逗号来解析CSV? [英] How to parse CSVs with newline and commas inside a field in Perl?

查看:141
本文介绍了如何在Perl的字段中使用换行符和逗号来解析CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Perl. This is a sample csv entry similar to mine. I would like to parse this, tried briefly Text::CSV, but no luck. The issue here is newline and commas inside fields. How could 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

推荐答案

此代码(直接从Text :: CSV文档中获取):

This code (taken directly from Text::CSV documentation):

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

(我想是)您想要实现的目标.

Which (I'm guessing) is what you want to achieve.

这篇关于如何在Perl的字段中使用换行符和逗号来解析CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆