无法摆脱while循环?

时间:2013-03-31 14:08:45

标签: 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 $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发现$_中的第一个匹配“我们”时,$count现在等于1,当它循环回来时,因为没有/g,它是如何响应的?还是因为它不知道如何回应而完全陷入困境?

1 个答案:

答案 0 :(得分:3)

正则表达式

/we/g
标量上下文中的

将迭代匹配,使正则表达式成为迭代器。正则表达式

/we/

将没有迭代质量,但只是匹配与否。因此,如果它匹配一次,它将始终匹配。因此无限循环。尝试

my $count;
while (/(.*?we)/) {
    print "$1\n";
    exit if $count++ > 100;   # don't spam too much
}

如果您只想计算匹配数,可以执行以下操作:

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

或者

my @matches = /we/g;
my $count = @matches;
相关问题