http://www.perlmonks.org?node_id=924182

ambrus has asked for the wisdom of the Perl Monks concerning the following question: (data structures)

How to check whether a hash is empty (has no keys)?

Originally posted as a Categorized Question.

  • Comment on How to check whether a hash is empty (has no keys)?

Replies are listed 'Best First'.
Re: How to check whether a hash is empty (has no keys)?
by ambrus (Abbot) on Sep 05, 2011 at 10:32 UTC

    Just use the name of the hash in scalar context, such as

    if (%foo) { # %foo has at least one key } else { # %foo has no keys }

    If you want to be very explicit, you can also write

    if (!!%foo) { ... }
    or
    if (scalar %foo) { ... }
    or
    if (0+%foo) { ... }
Re: How to check whether a hash is empty (has no keys)?
by davido (Cardinal) on Sep 06, 2011 at 02:13 UTC
    keys, in scalar context returns the number of keys in the hash.
    if( keys %hash ) { # There are keys } else { # There are no keys }