2017-06-14 28 views
1

我得到了一些行爲,我不理解的Perl:

>>> my @words = ('hello', 'there'); 
>>> $words[0] =~ /(el)/; print $1; 
el 
>>> $words[1] =~ /(el)/; print $1; 
undef 

,但在一個循環:

>>> my @words = ('hello', 'there'); 
>>> foreach my $word (@words){ 
>>> $word =~ /(el)/; 
>>> print "$1\n"; 
>>> } 
el 
el 

這是怎麼回事?以及如何我,在循環中,得到$ 1是不確定的,當它沒有在最近的正則表達式匹配,所以這樣的事情會工作:

foreach my $word (@words) { 
    $word =~ /(el)/; 
    if ($1) { 
     print "$word matched\n"; 
    } else { 
     print "$word did not match\n"; 
    } 
} 

回答

1

循環沒有什麼特別之處。

use strict; 
use warnings; 
use feature qw(say); 

my @words = ('hello', 'there'); 
$words[0] =~ /(el)/; say $1 // "[undef]"; 
$words[1] =~ /(el)/; say $1 // "[undef]"; 

my @words = ('hello', 'there'); 
foreach my $word (@words){ 
    $word =~ /(el)/; 
    say $1 // "[undef]"; 
} 

輸出:

el 
el 
el 
el 

$1和朋友只改變了一個成功的匹配,所以要

for my $word (@words) { 
    if ($word =~ /el/) { 
     print "$word matched\n"; 
    } else { 
     print "$word did not match\n"; 
    } 
} 
+0

我使用的邏輯是有點不僅僅是印刷更復雜比賽。這是我用來試圖瞭解發生了什麼的簡化情況。有什麼辦法可以做我想做的事嗎?即每當我得到一個匹配時設置'$ 1','$ 2'(或別的東西),如果我沒有得到匹配,每次迭代都將它們設置爲'undef'? – ewok

+1

'my($ capture)= $ word =〜/(el)/'和'my $ capture = $ word =〜/(el)/? $ 1:undef;'設置'$ capture'以你所描述的想要設置'$ 1'的方式。 – ikegami

+0

完美。這是否意味着我可以使用'my @matches = $ word =〜/(list)(of)(match)(patterns)/;'來獲取匹配數組? – ewok

0

一種方法是避免特殊編號完全變量,它們在運行之間不會重置。相反,使用一個局部變量,並在每個循環的開始復位:

use warnings; 
use strict; 

my @words = qw(
    one 
    two 
    three 
); 

for my $w (@words){ 
    my $store; 

    if (($store = $w) =~ /(t)/){ 
     print "$store\n"; 
    } 
    else { 
     print "no match\n"; 
    } 
} 

輸出:

two 
three 
0

檢查匹配的回報:

if ($word =~ /(el)/) { 
    print "$word matched with [$1]\n"; 
} else { 
    print "$word did not match\n"; 
} 

我懷疑你的測試環境在分別運行它們時會做得更多,包括重新設置$1等等。