Regex 不能';你不能退出while循环吗?

Regex 不能';你不能退出while循环吗?,regex,perl,while-loop,Regex,Perl,While Loop,我尝试了以下两个脚本。脚本1得到了我预期的结果。脚本2没有-可能卡在while循环中 $_= "Now we are engaged in a great civil war; we will be testing whether that nation or any nation so conceived and so dedicated can long endure. "; my $count = 0; while (/we/ig){ $count++ }; print

我尝试了以下两个脚本。脚本1得到了我预期的结果。脚本2没有-可能卡在while循环中

$_= "Now we are engaged in a great civil war; we will be testing whether
that nation or any nation so conceived and so dedicated can long endure. ";

my $count = 0;
while (/we/ig){
    $count++
    };
print $count;
输出
2

$_= "Now we are engaged in a great civil war, we will be testing whether
that nation or any nation so conceived and so dedicated can long endure";

my $count = 0;
while (/we/){
    $count++
    };
print $count;
我的理解是
/g
允许全局匹配。但我对剧本2很好奇, 当Perl在
$\uuUcode>和
$count
中找到第一个匹配项“we”后,当它返回时,由于没有
/g
,它将如何响应?还是因为它不知道如何响应而被卡住了?

正则表达式

/we/g
/we/
在标量上下文中,将迭代匹配项,使正则表达式成为迭代器。正则表达式

/we/
将没有迭代质量,但将只是匹配或不匹配。因此,如果它匹配一次,它将始终匹配。因此,无限循环。试一下

my $count;
while (/(.*?we)/) {
    print "$1\n";
    exit if $count++ > 100;   # don't spam too much
}
如果您只想计算匹配项,可以执行以下操作:

my $count = () = /we/g;


匹配返回的内容取决于三件事:/g与否,列表上下文与否,以及是否有捕获参数(所有内容都在文档中描述)