Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: What is the most efficient way to see if a hash is empty?

by Anonymous Monk
on Apr 28, 2009 at 18:26 UTC ( [id://760696]=note: print w/replies, xml ) Need Help??


in reply to What is the most efficient way to see if a hash is empty?

if (each %hash) { } seems to have the most stable performance when comparing a mix of empty, filled and mega filled hashes on my computer.
  • Comment on Re: What is the most efficient way to see if a hash is empty?

Replies are listed 'Best First'.
Re^2: What is the most efficient way to see if a hash is empty?
by ELISHEVA (Prior) on Apr 28, 2009 at 21:07 UTC
    Here's why each is not a good idea:

    Suppose you were to use each? Each call to each remembers its position within a hash. Only the first call would actually check to see if the hash was empty. The second and later calls would only be checking to see if there was a next element. So if statement #2 would return false if empty or if there were only one element. If statement #3 would return false there were 0,1, or 2 elements.

    But the problems run even deeper. Any function inside the conditional block will miss the first key-value pair if it tries to use a while each loop . Bugs like this are hard to track down because the confused while loop may not be in your own code - it could be in a third party subroutine! Code like this:

    use strict; use warnings; sub printAll; my %h=(a=>1, b=>2, c=>3); my @aKeys = keys %h; print "full set of keys: <@aKeys>\n"; print "print all key-value pairs:\n"; printAll(\%h) if (each %h); # subroutine using while each loop # possibly buried somewhere deep in a third party module sub printAll { my $h=shift; while (my ($k, $v) = each(%$h)) { print "$k, $v\n"; } }

    outputs

    full set of keys: <c a b> print all key-value pairs: a, 1 b, 2 #whoops - no c, 3 printed out!!!

    Best, beth

      Good call++.

Re^2: What is the most efficient way to see if a hash is empty?
by Your Mother (Archbishop) on Apr 28, 2009 at 20:07 UTC

    That's what I suggested trying in the CB to ELISHEVA last night. :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-20 11:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found