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
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With