给定/何时具有未定义的值

时间:2012-06-22 14:44:21

标签: perl warnings initialization

在以下代码中,我收到uninitialized value警告,但仅在第二个given/when示例中。这是为什么?

#!/usr/bin/env perl
use warnings;
use 5.12.0;

my $aw;

given ( $aw ) {
    when ( 'string' ) { 
        say "string"; 
    }
    when ( not defined ) { 
        say "aw not defined"; 
    }
    default { 
        say "something wrong"; 
    }
}

given ( $aw ) {
    when ( /^\w+$/ ) { 
        say "word: $aw"; 
    }
    when ( not defined ) { 
        say "aw not defined";
    }
    default { 
        say "something wrong";
    }
}

我得到的输出是:

aw not defined
Use of uninitialized value $_ in pattern match (m//) at ./perl.pl line 20.
aw not defined

2 个答案:

答案 0 :(得分:3)

given/when使用“smartmatch operator”:~~

undef ~~ string是:

undef     Any        check whether undefined
                     like: !defined(Any)

因此这里没有警告。

undef ~~ regex是:

 Any       Regexp     pattern match                                     
                      like: Any =~ /Regexp/

尝试匹配undef时会产生警告。

答案 1 :(得分:1)

呼叫when (EXPR)通常等于when ($_ ~~ EXPR)undef ~~ 'string'!defined('string'),因此您不会收到警告,但undef ~~ /regexp/undef =~ /regexp/,因此您会收到警告。

请参阅Switch Statements in perlsynSmartmatch Operator in perlop