使用数组时的Perl模式匹配

vel*_*els 7 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__
Run Code Online (Sandbox Code Playgroud)

我期望的输出应该是


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";
}
Run Code Online (Sandbox Code Playgroud)

现在我按预期得到了输出.

TLP*_*TLP 6

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

删除/g修改器,它将按预期运行.