2012-06-22 14 views
6

निम्न कोड में, मुझे 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 

उत्तर

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

तो उसे ठीक करने के लिए शीर्ष पर 'परिभाषित' चेक डालना चाहिए? – simbabque

+0

@simbabque, हाँ जो चेतावनी को हटा देगा। – Qtax

1

कॉलिंग when (EXPR) आमतौर पर when ($_ ~~ EXPR) के बराबर है। और undef ~~ 'string'!defined('string') है इसलिए आपको चेतावनी नहीं मिलती है, लेकिन undef ~~ /regexp/undef =~ /regexp/ है इसलिए आपको चेतावनी मिलती है।

Switch Statements in perlsyn और Smartmatch Operator in perlop देखें।

संबंधित मुद्दे