in reply to setting values in anonymous hash

There comes a time when one must display one's ignorance without fear. I suspect this is my time :)

I think I am missing something fundamental. First, I don't see why %tmp is necessary, nor do I I understand resetting the $k and $v before the while loop starts over -- don't they get reset automatically?

In other words, why wouldn't this work:

while (my $ref2 = $sth2->fetchrow_hashref()) { while (my ($k, $v) = each %$ref2) { $ref2->{$k} = '' if $v == undef; } }
?

Replies are listed 'Best First'.
Re: Re: setting values in anonymous hash
by Dominus (Parson) on Nov 28, 2000 at 19:50 UTC
    Says snax:
    > why wouldn't this work:
    > $ref2->{$k} = '' if $v == undef;
    It doesn't work because if $v was "hello", then you have just scrubbed it out and replaced it with the empty string.

    You should never compare anything for equality with undef, because 0 == undef is true, and "fish" == undef is also true. This is because undef behaves like 0 in a numeric context, and so do most strings. Even "" eq undef is true, which probably is not what you want.

    The only way to check to see if something is undef is to use the defined operator:

    $ref2->{$k} = '' if not defined $v;
      Oy. That would be bad indeed. I used some test code on the command line and was having trouble getting defined to return false values, so settled on the equality test.

      Context, as always, is important, as you demonstrate most eloquently.

Re: Re: setting values in anonymous hash
by agoth (Chaplain) on Nov 28, 2000 at 18:28 UTC
    that way works, ish, but just look at the warnings under -w?

    I had left the variable reset in by mistake!

    PS: works a treat though this way....

    while (my ($k, $v) = each %$ref2) { $ref2->{$k} = '' if (!defined $ref2->{$k}); } push @{ $tablist{$user_table} }, $ref2;

    Cheers..

    PPS: and even better this way, thanks!!!!

    for (keys %$ref2) { $ref2->{$_} = '' if (!defined $ref2->{$_}); } push @{ $tablist{$user_table} }, $ref2;

    PPPS: maybe down to one line if I was using 5.5! (untested this last one)

    $ref2->{$_} = '' unless (defined $ref2->{$_}) for (keys %$ref2);