Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

given/when with undefined value

In the following code, I get an uninitialized value warning, 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
like image 266
sid_com Avatar asked Jun 22 '12 14:06

sid_com


People also ask

What does it mean when a value is undefined?

In computing (particularly, in programming), undefined value is a condition where an expression does not have a correct value, although it is syntactically correct. An undefined value must not be confused with empty string, Boolean "false" or other "empty" (but defined) values.

How do you solve for undefined values?

To find the points where the numerical expression is undefined, we set the denominator equal to zero and solve. Once we find the points where the denominator equals zero, we can say that our numerical expression is valid for all numbers except the numbers where it is undefined.

Can we use undefined value to a variable?

You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not initialized, and the if statement evaluates to true.

What happens when you add undefined to a number?

You should define test as 0 to begin with so that it starts out as an object of type Number . Adding numbers to undefined results in NaN (not-a-number), which won't get you anywhere.


1 Answers

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

undef ~~ string is:

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

Thus there is no warning here.

undef ~~ regex is:

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

And a warning is produced when trying to match on undef.

like image 185
Qtax Avatar answered Oct 13 '22 16:10

Qtax