14

正規表現パターンが一致しない理由がわかりません。また、出力$foundは初期化されていないと不平を言いますが、そうしたと思います。これまでの私のコードは次のとおりです。

use strict;
use warnings;

my @strange_list = ('hungry_elephant', 'dancing_dinosaur');

my $regex_patterns = qr/
    elephant$
    ^dancing
    /x;

foreach my $item (@strange_list) {
    my ($found) = $item =~ m/($regex_patterns)/i;
    print "Found: $found\n";
}

これが私が得る出力です:

Use of uninitialized value $found in concatenation (.) or string at C:\scripts\perl\sandbox\regex.pl line 13.
Found:
Use of uninitialized value $found in concatenation (.) or string at C:\scripts\perl\sandbox\regex.pl line 13.
Found:

$found別の方法で初期化する必要がありますか? また、正規表現として解釈される複数行の文字列を正しく作成していますか?

どうもありがとう。

4

3 に答える 3

17

パターン マッチ ( =~) が何にも一致しない場合、スカラーには何も格納されない$foundため、Perl は、値が与えられていない変数を補間しようとしていると文句を言っています。

条件付きでない限り、後置を使用することでこれを簡単に回避できます。

$found = "Nothing" unless $found
print "Found: $found\n";

上記のコードは、まだ値がない場合に$found のみ、値「Nothing」を割り当てます。これで、どちらの場合でも、print ステートメントは常に正しく機能します。

単純な if ステートメントを使用することもできますが、それはより冗長に見えます。

if( $found ) {
   print "Found: $found\n";
}
else {
   print "Not found\n";
}

最もクリーンな別のオプションは、パターン マッチを if ステートメントに配置することです。

if( my ($found) = $item =~ m/($regex_patterns)/i ) {
   # if here, you know for sure that there was a match
   print "Found: $found\n";
}
于 2013-07-08T14:00:39.947 に答える
2

正規表現に区切り記号がありません。|象と踊りの間に挿入。

Foundさらに、何かが本当に見つかった場合にのみ印刷する必要があります。あなたはそれを修正することができます

print "Found: $found\n" if defined $found;
于 2013-07-08T14:05:17.973 に答える