2013-03-31 127 views
1

我试了下面两个脚本。脚本1得到了我期望的结果。脚本2没有 - 可能停留在while循环中?无法摆脱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,它是如何响应的第一场比赛“我们”?还是因为不知道如何回应而卡住?

+0

什么是匹配的回报取决于三个事情:/ g或不,列出上下文,以及是否捕获parens(全部在文档中描述) – ysth

回答

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; 
+0

非常感谢!需要学习如何测试我的假设:) –

+0

不客气。 – TLP