Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid an uninitialized value?

Tags:

perl

I use this scrub function 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?

like image 200
Sandra Schlichting Avatar asked Apr 24 '26 13:04

Sandra Schlichting


1 Answers

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.

like image 68
DrHyde Avatar answered Apr 26 '26 03:04

DrHyde