【问题标题】:Perl warning: Use of uninitialized value in concatenation (.) or stringPerl 警告:在连接 (.) 或字符串中使用未初始化的值
【发布时间】:2017-10-06 02:37:18
【问题描述】:

我无法弄清楚为什么正则表达式模式不匹配。此外,输出抱怨 $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?另外,我是否正确地创建了一个多行字符串来解释为正则表达式?

非常感谢。

【问题讨论】:

  • 你的多行字符串被解释为qr/elephant$^dancing/;,而你可能想要qr/elephant$|^dancing/;
  • 对于多行匹配,使用 /m 开关:my $regex_patterns = qr/elephant$^dancing/mx;
  • 有时最好关闭此警告。将此添加到您的 perl 标头 - 没有警告“未初始化”

标签: regex perl


【解决方案1】:

如果模式匹配 (=~) 不匹配任何内容,则不会在您的标量 $found 中存储任何内容,因此 Perl 抱怨您正在尝试插入一个未指定值的变量。

除非有条件,否则您可以使用后缀轻松解决此问题:

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

上面的代码将值“Nothing”分配给$found如果它还没有值。现在,无论哪种情况,您的打印语句都将始终正常工作。

您也可以只使用一个简单的 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";
}

【讨论】:

  • 能否举例说明如何将我的正则表达式添加到包含“除非”的行中?
  • @DirtyPenguin 您的正则表达式将在该行 before 行上。
  • 感谢您的详细解释。 :)
【解决方案2】:

您的正则表达式缺少分隔符。在大象和跳舞之间插入|

此外,只有在真正找到任何东西时,您才应该打印Found。你可以解决这个问题

print "Found: $found\n" if defined $found;

【讨论】:

    【解决方案3】:

    Double forward slash (//) 也可以用来初始化$found。它与unless 非常相似。唯一要做的就是修改print 行如下。

    print "Found: " . ($found // 'Nothing') . "\n";
    

    如果$found 未初始化,将打印“Nothing”。

    结果(Perl v5.10.1):

    Found: Nothing
    Found: Nothing
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多