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

What's the easiest way to see if a hash contains any data? Doing a loop and counting on $cnt seems inefficient so is there an easy way? Would if (!%hash) {} work?

Replies are listed 'Best First'.
Re: checking to see if a hash has data
by brian_d_foy (Abbot) on May 14, 2005 at 00:00 UTC

    If you want a count of the keys, use the keys() operator in scalar context.

    my $key_total = keys %hash;

    If you need something else, such as the count of the defined values, you have to do a bit more work.

    my $defined_count = grep { defined } values %hash;
    --
    brian d foy <brian@stonehenge.com>
Re: checking to see if a hash has data
by holli (Abbot) on May 13, 2005 at 23:58 UTC
    Would if (!%hash) {} work?
    Yes. Or use scalar keys %hash to get the number of entries.


    holli, /regexed monk/
Re: checking to see if a hash has data
by tlm (Prior) on May 14, 2005 at 00:25 UTC

    You just go ahead and try it from the command line (make sure that warnings are enabled):

    % perl -wle 'my %foo; if ( %foo ) { print "OK" } else { print "KO" }' KO % perl -wle 'my %foo = (1,2); if ( %foo ) { print "OK" } else { print +"KO" }' OK
    But you have to be careful, because sometimes perl will conjure keys from thin air. For example:
    % perl -wl print( %foo ? "OK" : "KO" ); my @bar = grep $_, @foo{ 1, 2, 3 }; print( %foo ? "OK" : "KO" ); ^D KO OK
    Notice how the second test succeeded, even though we never initialized %foo. For this reason, maybe something like this (also proposed by brian_d_foy) would be better:
    if ( grep defined, values %foo ) { # etc. }
    This test will succeed only if %foo contains at least one defined value.

    the lowliest monk

Re: checking to see if a hash has data
by borisz (Canon) on May 14, 2005 at 00:51 UTC
    if ( () = keys %hash ) { # has data } else { # no data }
    Boris