Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Testing Hash with empty value in HoH

by Anonymous Monk
on Jun 15, 2005 at 10:09 UTC ( #466851=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

With this code
#!/usr/bin/perl -w use strict; use Data::Dumper; my $hoh = { 'pk1' => { 'sk1' => [ 'val1', 'val2' ], 'sk2' => { 'tk1' => 'val1 val2 ', 'tk2' => 'val9,val7' }, 'sk3' => 'val10 val11', 'sk4' => 21 }, 'pk2' => {}, }; #print Dumper $hoh; foreach my $k ( keys %{$hoh} ) { if( $hoh->{$k} ) { print "$k\n"; }; }
How can I make it only print "pk1" since "pk2" has no value in it, without having to go through second loop. What's wrong with my test above? Now it prints both "pk1 and pk2"

Replies are listed 'Best First'.
Re: Testing Hash with empty value in HoH
by salva (Canon) on Jun 15, 2005 at 10:16 UTC
    a reference to an empty hash is a true value.

    Use values on scalar context to get the number of elements on the hash:

    foreach my $k ( keys %{$hoh} ) { if( $hoh->{$k} and values %{$hoh->{$k}}) { print "$k\n"; }; }
    updated following Limbic~Region advice.
      I agree with what you have said and how you have used your code, but for clarity believe you should add in scalar context. It may not be obvious to someone unfamiliar with Perl's DWYMery that in list context you get the list of values and in scalar context you only get the count.

      Cheers - L~R

Re: Testing Hash with empty value in HoH
by dorward (Curate) on Jun 15, 2005 at 10:18 UTC

    A reference to a hash, even an empty hash, is true. Try defreferencing it.

    my $foo = {}; print "OK\n" if (scalar %{$foo});
Re: Testing Hash with empty value in HoH
by monkey_boy (Priest) on Jun 15, 2005 at 10:16 UTC

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://466851]
Approved by jbrugger
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2021-12-03 21:45 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (30 votes). Check out past polls.