in reply to One liner to Check and undef hash elements

I'm sure somebody else will come up with something more optimal...

#1. if ((scalar grep {defined} values %{$hash}) == 0) { # all values are undef } #2. $hash = { map {$_ => undef} keys %{$hash} }; # now empty

Update: Changed > 0 to == 0, since the poster asked for "check if empty"

Update: Fixed precedence problem (pointed out by original poster). Works now.

Replies are listed 'Best First'.
Re: Re: hash problem
by Anonymous Monk on Apr 16, 2003 at 00:53 UTC
    Hi crenz, thanks for you reply. #2 works very nicely, but I can't make #1 work. Your code prints "empty" for both of these hashes.
    $hash->{'a'} = 1; $hash->{'b'} = undef; $hash->{'c'} = undef; $hash->{'d'} = undef; if (scalar grep {defined} values %{$hash} == 0) { print "empty\n"; } $hash->{'a'} = undef; $hash->{'b'} = undef; $hash->{'c'} = undef; $hash->{'d'} = undef; if (scalar grep {defined} values %{$hash} == 0) { print "empty\n"; }