开发者

How do I avoid an uninitialized value?

开发者 https://www.devze.com 2023-03-20 18:18 出处:网络
I use this scrub func开发者_StackOverflow中文版tion to clean up output from other functions. #!/usr/bin/perl

I use this scrub func开发者_StackOverflow中文版tion to clean up output from other functions.

#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

my %h = (
    a => 1,
    b => 1
    );

print scrub($h{c});

sub scrub {
    my $a = shift;

    return ($a eq '' or $a eq '~' or not defined $a) ? -1 : $a;
}

The problem occurs when I also would like to handle the case, where the key in a hash doesn't exist, which is shown in the example with scrub($h{c}).

What change should be make to scrub so it can handle this case?


You're checking whether $a eq '' before checking whether it's defined, hence the warning "Use of uninitialized value in string eq". Simply change the order of things in the conditional:

return (!defined($a) or $a eq '' or $a eq '~') ? -1 : $a;

As soon as anything in the chain of 'or's matches, Perl will stop processing the conditional, thus avoiding the erroneous attempt to compare undef to a string.


In scrub it is too late to check, if the hash has an entry for key key. scrub() only sees a scalar, which is undef, if the hash key does not exist. But a hash could have an entry with the value undef also, like this:

my %h = (
 a => 1,
 b => 1,
 c => undef
); 

So I suggest to check for hash entries with the exists function.

0

精彩评论

暂无评论...
验证码 换一张
取 消