I have a strange problem in matching a pattern.
我在匹配模式时遇到了一个奇怪的问题。
Consider the Perl code below
考虑下面的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__
The output I expect should be
我期望的输出应该是
Hello Good Hello Good Hello Good
But what I get is
但我得到的是
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
What I observed was that the pattern matches alternatively.
Can someone explain me what is the problem regarding this code.
To fix this I changed the function subroutine to something like this:
我观察到的是模式交替匹配。有人可以解释一下这段代码有什么问题。为了解决这个问题,我将函数子例程更改为:
sub function
{
my $string;
foreach my $pattern (@Array)
{
$string .= $pattern."\n";
}
while ($string =~ m/(\w+)\|(\w+)/g)
{
print $1."\n";
}
print "\n";
}
Now I get the output as expected.
现在我按预期得到了输出。
1 个解决方案
#1
6
It is the global /g
modifier that is at work. It remembers the position of the last pattern match. When it reaches the end of the string, it starts over.
它是全局/ g修饰符正在起作用。它记住了最后一次模式匹配的位置。当它到达字符串的末尾时,它会重新开始。
Remove the /g
modifier, and it will act as you expect.
删除/ g修饰符,它将按预期运行。
#1
6
It is the global /g
modifier that is at work. It remembers the position of the last pattern match. When it reaches the end of the string, it starts over.
它是全局/ g修饰符正在起作用。它记住了最后一次模式匹配的位置。当它到达字符串的末尾时,它会重新开始。
Remove the /g
modifier, and it will act as you expect.
删除/ g修饰符,它将按预期运行。