I have a statement in Perl like
if (($hh, $mm) = ($info{$item}{$p_expectedtime} =~ /(d+):(d+)/))
but when compiling, I get the message:
Use of uninitialized value in pattern match (m//)
Tried to add a define()
like
if (define($hh, $mm) && ($hh, $mm) = ($info{$item}{$p_expectedtime} =~ /(d+):(d+)/))
which is incorrect.
Here’s your code:
if (($hh, $mm) = ($info{$item}{$p_expectedtime} =~ /(d+):(d+)/))
And here’s the error message:
Use of uninitialized value in pattern match (m//)
Note, that the error says the uninitialised value is in the pattern match, not the assignment, so we can eliminate the first piece of the code from our investigations, leaving us with:
$info{$item}{$p_expectedtime} =~ /(d+):(d+)/
If it were $item
or $p_expectedtime
that were uninitialised then the error would talk about “uninitialised value in hash element”, so it’s not those that are undefined either.
No, the uninitialised value is the value that you’re comparing with the regex. It’s the value in $info{$item}{$p_expectedtime}
.
Tried to add a
define()
Two problems here. Firstly, you’re checking $hh
and $mm
which we’ve already eliminated from our investigations. And, secondly, the function you’re looking for is actually called defined()
(with a ‘d’). So you might want something like:
if (! defined $info{$item}{$p_expectedtime}) {
warn "$info{$item}{$p_expectedtime} is undefinedn";
} else {
# Original code here
}
The warning message is helpful in that it alerts you to an unanticipated issue; unfortunately, it is not specific enough to let you know exactly which “value” is uninitialized. There are 5 variables in that line to choose from.
As an educated guess, I suspect that there is no value for the hash key represented by the $p_expectedtime
variable. Here is a scenario which demonstrates that:
use warnings;
use strict;
use Data::Dumper qw(Dumper);
my $item = 'item';
my $p_expectedtime = 66;
my $hh;
my $mm;
my %info = (item => {notime => 5});
print Dumper(%info);
if (($hh, $mm) = ($info{$item}{$p_expectedtime} =~ /(d+):(d+)/)) {
print "matchn";
}
if (exists $info{$item}{$p_expectedtime}) {
print "existsn";
}
else {
print "not existsn";
}
The output is something like:
$VAR1 = {
'item' => {
'notime' => 5
}
};
Use of uninitialized value in pattern match (m//) at ...
not exists
Dumper
is a useful tool for helping to debug Perl code which has a data structure like a hash.
To check if a hash key exists or not, you can use exists.
0