1

我在下面有这段代码:

my $file = 'c:\test.log';
open (FILE, "<", $file) or die $!;
my @list = grep /\bAdobe\b/, <FILE>;
my $days;
foreach (@list) {
$days = $_;
print "$days\n";
}

预期结果是:

"Adobe","10:10:10, 11/10/2011","Ready"

我想用下面的代码用逗号分割结果:

my @sample = split(',', $days);

预期结果是:

"Adobe"
"10:10:10
11/10/2011"
"Ready"

但这不是我想做的:

我想像这样打印输出:

"Adobe"
"10:10:10, 11/10/2011"
"Ready"

如果不使用/安装任何像 Text::CSV 这样的模块,我怎么能做到这一点。

请指教,谢谢。

4

4 回答 4

6

理想情况下,您将使用 CSV 解析器,请参阅Text::CSV。或者只要所有字段都被双引号括起来,那么您可以使用带有稍微复杂的正则表达式的拆分,它会检查分隔符:

split /(?<="),(?=")/, $days;
于 2011-11-22T12:00:04.213 回答
4

我相信它适用于Text::CSV模块。像这个例子这样的东西应该有效:

use Text::CSV;

my $file = 'c:\test.log';
open (my $FILE, "<", $file) or die $!;
my $csv = Text::CSV->new;

while (my $row = $csv->getline($FILE)) {
  my @sample = @$row;
  next if $sample[0] !~ /\bAdobe\b/;
  # do whatever you want
}
于 2011-11-22T11:55:54.773 回答
2

无需从 CPAN 安装 Text::CSV(尽管,如果您有该限制,那么您确实需要修复该限制),因为也可以使用标准发行版中的Text::ParseWords模块。

于 2011-11-22T12:41:26.927 回答
1

Since the string "Adobe","10:10:10, 11/10/2011","Ready" is valid as perl code, you can use eval:

my $file = 'c:\test.log';
open my $fh, "<", $file or die $!;
for (grep /\bAdobe\b/, <FILE>) {
    my @sample = eval;
    # code here
}

But only do this for data you are sure is in a valid format.

Output from Data::Dumper:

$VAR1 = [
          "Adobe",
          "10:10:10, 11/10/2011",
          "Ready"
        ];
于 2011-11-22T18:48:21.323 回答