Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Answer: How do I find out if a hash is empty?

by ysth (Canon)
on Nov 04, 2003 at 09:56 UTC ( #304363=categorized answer: print w/replies, xml ) Need Help??

Q&A > hashes > How do I find out if a hash is empty? - Answer contributed by ysth

Preferably with  if (!keys %hash) { print "Empty" } .

This has the drawback of actually going through fetching all the keys for a tied hash, but the alternative (if (!%hash) { print "Empty" }) doesn't work at all for tied hashes.

If tied hashes aren't a concern, either way will do, but there is a difference to be aware of: the keys version will reset the hash's iterator (see each) while the other way will leave it unchanged.

Replies are listed 'Best First'.
Re: Answer: How do I find out if a hash is empty?
by Roy Johnson (Monsignor) on Nov 04, 2003 at 14:11 UTC
    This has the drawback of actually going through fetching all the keys for a tied hash, but the alternative (if (!%hash) { print "Empty" }) doesn't work at all for tied hashes.

    Actually, using !keys is over 6x faster than using !%hash, and it does not get slower with a larger hash, so it is pretty clear that Perl does not have to iterate through all the keys to get the key count. Another way to do it would be to say !each %hash (which, of course, advances the iterator on non-empty hashes). However, the keys method is about twice as fast as that.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (11)
As of 2019-02-18 14:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I use postfix dereferencing ...









    Results (100 votes). Check out past polls.

    Notices?