in reply to Re: What is the most efficient way to see if a hash is empty?
in thread What is the most efficient way to see if a hash is empty?
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: What is the most efficient way to see if a hash is empty?
by Your Mother (Archbishop) on Apr 28, 2009 at 22:04 UTC |