Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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


In reply to Re^2: What is the most efficient way to see if a hash is empty? by ELISHEVA
in thread What is the most efficient way to see if a hash is empty? by ELISHEVA

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

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

    No recent polls found