Set / when undefined

In the following code, I get a warning of uninitialized value , but only in the second given/when example. Why is this?

 #!/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"; } } 

The output I get is:

 aw not defined Use of uninitialized value $_ in pattern match (m//) at ./perl.pl line 20. aw not defined 
+6
source share
2 answers

given / when uses the smartmatch operator ": ~~ .

undef ~~ string :

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

So there are no warnings here.

undef ~~ regex :

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

When you try to map to undef , a warning appears.

+3
source

The when (EXPR) call is usually equal to when ($_ ~~ EXPR) . And undef ~~ 'string' is !defined('string') , so you will not get a warning, but undef ~~ /regexp/ is undef =~ /regexp/ so that you get a warning.

See Switch statements in perlsyn and Smartmatch statement in perlop .

+1
source

Source: https://habr.com/ru/post/918765/


All Articles