2013-02-18 68 views
0

下面我有一个while循环之后(字符串或数字)到一个数组:存储值执行while循环

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

后while循环结束后,我将匹配出头像“错误...”,我想将它们存储到数组或列表或哈希中。我怎样才能做到这一点?

回答

1

只要将数据推入数组。

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/ } <>; 
+0

有一个错字在第三个例子中,它应该是'$ _'而不是'$ line'。 – Toto 2013-02-18 09:30:11

+0

@ M42,感谢Borodin修复它。 – ikegami 2013-02-18 11:47:05

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

print "$_\n" for @arr;