我得到了一些行爲,我不理解的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','$ 2'(或別的東西),如果我沒有得到匹配,每次迭代都將它們設置爲'undef'? – ewok
'my($ capture)= $ word =〜/(el)/'和'my $ capture = $ word =〜/(el)/? $ 1:undef;'設置'$ capture'以你所描述的想要設置'$ 1'的方式。 – ikegami
完美。這是否意味着我可以使用'my @matches = $ word =〜/(list)(of)(match)(patterns)/;'來獲取匹配數組? – ewok