English 中文(简体)
带引号的地体
原标题:Parsing strings with quote characters inside fields

附录一

$ cat toParse.txt
1 2 3 4 5
1 "2 3" 4 5
1 2" 3 " 4 5 

头两条线很容易穿透:<代码>Text:CSV可处理。 例如,我尝试:

use strict; 
use Text::CSV; 
while() { 
    chomp $_; 
    my $csv = Text::CSV->new({ sep_char =>    , quote_char =>  "  , binary => 1});
    $csv->parse($_); 
    my @fields = $csv->fields(); 
    my $badArg = $csv->error_input(); 
    print "fields[1] = $fields[1]
"; 
    print "Bad argument: $badArg

"; 
}

然而,如果所引述的特性载于,则CSV会感到非常混乱。

上述节目印刷如下:

fields[1] = 2
Bad argument:

fields[1] = 2 3
Bad argument:

fields[1] =
Bad argument: 1 2" 3 " 4 5

是否有任何建议? 我与最后的<代码>fields ***一样,以2”3“为代表,换言之,我要把这条线与任何未载于引示的白色空间分开。

最佳回答

你们所希望的不是特别志愿人员,因此,你们需要把自己的教义规范下来。

这应当针对你的具体情况:

use strict;

while (<DATA>) { 
    chomp $_;
    my @fields = /([^s"]+|(?:[^s"]*"[^"]*"[^s"]*)+)(?:s|$)/g;
    print "$_
" for @fields;
    print "
";
}

__DATA__

1 2 3 4 5
1 "2 3" 4 5
1 2" 3 " 4 5 
1 2" 3 "4 5 
1 2" 3 "4" 5" 6
1 2" 3 "4"" 5"" 6

......其产出是:

1
2
3
4
5

1
"2 3"
4
5

1
2" 3 "
4
5

1
2" 3 "4
5

1
2" 3 "4" 5"
6

1
2" 3 "4""
5""
6

Click here测试。

问题回答

改动引文是“第三行”

1
2"
3
"
4
5

然而,现在第二行将

1 
"2
3"
4
5

因此,你似乎有一条线,“是限定语,是限定语。

因此,你们的档案被打破,你将不得不cl。





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...