1

我尝试了以下两个脚本。脚本 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 找到第一个匹配 "we"$_并且$count现在等于 1 之后,当它循环返回时,由于没有/g,它如何响应?还是因为不知道如何响应而卡住了?

4

1 回答 1

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;
于 2013-03-31T14:16:32.040 回答