Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Fellow Monks,

I have just spent an hour debugging a very strange problem, only to discover that I have been bitten by the behaviour of each. While all this is properly documented (each), I was not aware of it, so I thought I'd bring it up here as a caveat to remember.

The subroutine in the following snippet works only once (or rather every other time).

use strict; use warnings; our %hash = ( 1=> 2, 3=>4 ); sub find_2{ while (my ($key,$val) = each(%hash)) { return "The key for 2 is $key\n" if $val == 2; } die "could not find 2"; } print find_2; print find_2;
After the first call, it dies:
The key for 2 is 1 could not find 2 at each.pl line 11.
What happens here is that the subroutine does not search through the whole hash (it short-cicuits for performance reasons by returning the solution as soon as it has found it), and as a result, the next call to each on the same hash (even in completely different parts of the code!) will not start at the beginning again, but pick up where the first call left off.

Solution: Either go through the whole hash, or rewind it after using each:

if ($val == 2){; #rewind each my $a = scalar keys %hash; return "The key for 2 is $key\n" }

In reply to Ouch! Each! Reentrant it is not by Thilosophy

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 about the Monastery: (7)
As of 2024-03-28 11:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found