奇怪的perl foreach行为使用模式匹配

时间:2013-09-11 20:24:53

标签: regex arrays oracle perl

我正在编写一个perl脚本,它将查看Oracle 11g数据库警报日志并报告错误。我遇到问题的代码如下:

if ($_ =~ (m/WARNING/ or m/ORA/)){print $_ . "\n";}

我希望if语句(第31行)产生:

Mon Sep 01 01:01:01 1111 WARNING: THIS IS AN ERROR MESSAGE
Mon Sep 04 04:04:04 4444 WARNING: THIS IS ANOTHER ERROR MESSAGE
Mon Sep 05 05:05:05 5555 ORA-123456 HAS OCCURRED.
Mon Sep 06 06:06:06 6666 WARNING MESSAGE!

然而它正在产生:

Mon Sep 01 01:01:01 1111 WARNING: THIS IS AN ERROR MESSAGE
Mon Sep 02 02:02:02 2222 log switch has occurred
Mon Sep 03 03:03:03 3333 AUDIT: Purge complete
Mon Sep 05 05:05:05 5555 ORA-123456 HAS OCCURRED.

如果我为每个模式使用单独的if语句,我会得到所需的结果:

if ($_ =~ (m/WARNING/)){print $_ . "\n";}
if ($_ =~ (m/ORA/)){print $_ . "\n";}

我不知道为什么会这样。

数据

Mon Sep 01 01:01:01 1111
WARNING: THIS
IS
AN
ERROR
MESSAGE
Mon Sep 02 02:02:02 2222
log switch
has
occurred
Mon Sep 03 03:03:03 3333
AUDIT: Purge complete
Mon Sep 04 04:04:04 4444
WARNING: THIS
IS
ANOTHER
ERROR
MESSAGE
Mon Sep 05 05:05:05 5555
ORA-123456 HAS
OCCURRED.
Mon Sep 06 06:06:06 6666
WARNING
MESSAGE!

脚本

use strict;
use warnings;

my $input = $ARGV[0];
my $output = 'output.out';
my $log_line;
my @log_entries;

open INPUT, $input or die "Could not open $input: $!";
while(<INPUT>)
{
    chomp;
    if ($_ =~ m/^\w{3} \w{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}/)
    {
        {
            push (@log_entries, $log_line);
        }
        $log_line = "$_ ";
    }
    else
    {
        $log_line .= "$_ ";
    }
}
push (@log_entries, $log_line);
close (INPUT);

foreach (@log_entries)
{
    next if not defined($_);
    if ($_ =~ (m/WARNING/ or m/ORA/)){print $_ . "\n";} #No idea why this doesn't work
#   if ($_ =~ (m/WARNING/)){print $_ . "\n";}
#   if ($_ =~ (m/ORA/)){print $_ . "\n";}
}

3 个答案:

答案 0 :(得分:5)

缺少绑定操作符(=~!~),

m/.../

装置

$_ =~ m/.../

这意味着

$_ =~ (m/WARNING/ or m/ORA/)

装置

$_ =~ ($_ =~ m/WARNING/ or $_ =~ m/ORA/)

所以你最终会做

$_ =~ ''

$_ =~ '1'

这显然不是你想要的。请改用以下其中一项:

$_ =~ m/WARNING/ or $_ =~ m/ORA/
   -or-
/WARNING/ || /ORA/
   -or-
/WARNING|ORA/

答案 1 :(得分:2)

这是使用或操作将这两行组合在一起的方法。

if ($_ =~ (m/(WARNING|ORA)/)){print $_ . "\n";}

答案 2 :(得分:1)

你必须在匹配结果上定义布尔表达式而不是匹配运算符 - 使用

if (($_ =~ m/WARNING/) or ($_ =~ m/ORA/)) {print $_ . "\n";}

而不是

if ($_ =~ (m/WARNING/ or m/ORA/)){print $_ . "\n";}