Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

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

by ambrus (Abbot)
on Sep 05, 2011 at 10:27 UTC ( [id://924182]=perlquestion: print w/replies, xml ) Need Help??

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 }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 12:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found