我不明白正则表达式模式不匹配的原因。此外,输出抱怨$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: $foundn";
}
这是我得到的输出:
Use of uninitialized value $found in concatenation (.) or string at C:scriptsperlsandboxregex.pl line 13.
Found:
Use of uninitialized value $found in concatenation (.) or string at C:scriptsperlsandboxregex.pl line 13.
Found:
我需要用另一种方式初始化$found
吗?此外,我是否正确地创建了一个多行字符串以解释为regex?
非常感谢。
如果模式匹配(=~
)与任何内容都不匹配,则标量$found
中不会存储任何内容,因此Perl抱怨您试图对未给定值的变量进行插值。
你可以通过使用后缀轻松绕过这一点,除非有条件:
$found = "Nothing" unless $found
print "Found: $foundn";
上面的代码将值"Nothing"分配给$found
only,如果它还没有值的话。现在,无论在哪种情况下,您的打印报表都将始终正确工作。
您也可以只使用一个简单的if语句,但这似乎更为冗长:
if( $found ) {
print "Found: $foundn";
}
else {
print "Not foundn";
}
另一个可能最干净的选项是将您的模式匹配放在if语句中:
if( my ($found) = $item =~ m/($regex_patterns)/i ) {
# if here, you know for sure that there was a match
print "Found: $foundn";
}
正则表达式缺少分隔符。在大象和舞蹈之间插入|
。
此外,只有在确实找到任何内容的情况下,才应打印Found
。你可以通过来解决这个问题
print "Found: $foundn" if defined $found;
双正斜杠(//
)也可用于初始化$found
。它与unless
非常相似。唯一要做的就是如下修改print
行。
print "Found: " . ($found // 'Nothing') . "n";
如果$found
未初始化,则将打印"Nothing"。
结果(Perl v.10.1):
Found: Nothing
Found: Nothing