使用数组时的Perl模式匹配

时间:2012-03-13 03:59:22

标签: regex perl

我在匹配模式时遇到一个奇怪的问题。

考虑下面的Perl代码

#!/usr/bin/perl -w

use strict;
my @Array = ("Hello|World","Good|Day");

function();
function();
function();

sub function 
{
  foreach my $pattern (@Array)  
  {
    $pattern =~ /(\w+)\|(\w+)/g;
    print $1."\n";
  }
    print "\n";
}

__END__

我期望的输出应该是


Hello
Good

Hello
Good

Hello
Good

但我得到的是

Hello
Good

Use of uninitialized value $1 in concatenation (.) or string at D:\perlfiles\problem.pl li
ne 28.
Use of uninitialized value $1 in concatenation (.) or string at D:\perlfiles\problem.pl li
ne 28.

Hello
Good

我观察到的是模式交替匹配 有人可以解释一下这个代码的问题是什么 为了解决这个问题,我将函数子程序改为:

sub function 
{
    my $string;
    foreach my $pattern (@Array)
    {
        $string .= $pattern."\n";
    }
    while ($string =~ m/(\w+)\|(\w+)/g)
    {
            print $1."\n";
    }
    print "\n";
}

现在我按预期获得输出。

1 个答案:

答案 0 :(得分:6)

正在使用全局/g修饰符。它记住了最后一次模式匹配的位置。当它到达字符串的末尾时,它会重新开始。

删除/g修饰符,它会按预期运行。

相关问题