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

标签 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";}
}

最佳答案

缺少绑定(bind)运算符(=~!~),

m/.../

表示

$_ =~ m/.../

也就是说

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

表示

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

所以你最终会做

$_ =~ ''

$_ =~ '1'

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

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

关于regex - 使用模式匹配的奇怪 perl foreach 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18750558/

相关文章:

python - numpy 中是否有函数可以替换 numpy 数组的下对角线和上对角线值?

java - 根据条件分组/不同列

java - 加载文件到oracle数据库

javascript - 将变量传递给.replace,如何使var与replace一起使用?

regex - 这是什么意思?使用表达式匹配什么字符串?

php - 对多维数组中的行进行分组,并对每组中的 "count"个元素求和

php - 如何以相反的顺序遍历我的数组?

sql - Oracle 中的 SUM(COUNT())

javascript - 在 javascript 中否定正则表达式中的模式时出现错误

javascript - 计算字符串中特定单词的出现次数