2017-06-14 5 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; '$ 1'を設定したいと言った方法で' $ capture'を設定します。 – ikegami

+0

完璧。それは、 'my @matches = $ word =〜/(リスト)(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のリセットを含みます。

関連する問題