0

我在下面有一个while循环:

while (<>)
{
    my $line = $_;
    if ($line =~ m/ERROR 0x/)
    {
        $error_found +=1;
    }
}

在while循环完成后,我将匹配“错误...”之类的内容,我想将它们存储到数组或列表或哈希中。我怎样才能做到这一点?

4

2 回答 2

2

只需将数据推送到数组中。

my @errors;
while (<>)
{
    my $line = $_;
    if ($line =~ m/ERROR 0x/)
    {
        push @errors, $line;
    }
}

稍微清理一下:

my @errors;
while (my $line = <>)
{
    if ($line =~ /ERROR 0x/)
    {
        push @errors, $line;
    }
}

或者甚至可能

my @errors;
while (<>)
{
    if (/ERROR 0x/)
    {
        push @errors, $_;
    }
}

最后,意识到这grep在这里会做得很好:

my @errors = grep { /ERROR 0x/ } <>;
于 2013-02-18T07:53:04.760 回答
0
my @arr;
while (<>)
{
    my $line = $_;
    if ($line =~ m/ERROR 0x/)
    {
        push(@arr,$line) ;
    }
}

print "$_\n" for @arr;
于 2013-02-18T07:32:00.640 回答