2013-03-31 125 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