Search code examples
perlwarningsdbidbix-class

perl waring : "Use of unintitialized value in string ne" for condition check for column with the null value


I am trying to fetch certain column from a table , some of the column might have the null value.Hence before filling my main data, I am checking the hash for null value.As some of the key is having null value and giving warning.

Is there any way to check if the hash key has no value in it to prevent warning.

    my $counter = 1;
    while ( my $hashRef = $queryHandle1->fetchrow_hashref) {

       foreach my $key (keys %{$hashRef} ) {
        if ( $hashRef->{$key} ne "" ) { #some of the coloumn of table has null value
                    #warning is coming for the if check
            $dbData{$counter}{$key} = $hashRef->{$key};
        }
        else {
            $dbData{$counter}{$key} = "";
        }

       }
       $counter++;
    }

Solution

  • Sure there is: the defined function.

    if (defined $hashRef->{$key}) {...}
    

    Or, since undef evaluates to false, you can use the short-circuiting OR operator to assign something else in one step without an explicit check.

    $dbData{$counter}{$key} = $hashRef->{$key} || '';
    

    Update:

    As suggested by the comments, the one-liner is dangerous if you have 0 values which also evaluate to false. So you can do this instead:

    $dbData{$counter}{$key} = defined $hashRef->{$key} ? $hashRef->{$key} : '';