gpt4 book ai didi

regex - 使用数组时的 Perl 模式匹配

转载 作者:行者123 更新时间:2023-12-04 12:11:45 24 4
gpt4 key购买 nike

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

考虑下面的 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__

我期望的输出应该是
HelloGoodHelloGoodHelloGood

But what I get is

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

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

现在我得到了预期的输出。

最佳答案

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

删除 /g修饰符,它将按照您的预期运行。

关于regex - 使用数组时的 Perl 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9678168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com