Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
Keep It Simple, Stupid
 
PerlMonks  

Re: Reset while loop to beginning of hash when using 'each'

by davido (Cardinal)
on Sep 25, 2003 at 19:23 UTC ( [id://294288]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Reset while loop to beginning of hash when using 'each'

According to the perldoc for each you can reset the each iterator function in one of the following ways:

  • Iterate over the entire hash. Upon final iteration, zero or null is returned depending on context, and the next call to each will start over again. You might find this to be slightly inconvenient if the point is to break out of a loop before iterating over all elements.
  • evaluate keys %hash.
  • evaluate values %hash.

You might think that evaluating keys for the hash is an inefficient way of resetting the each iterator. It might be, if you were to evaluate keys in list context. Don't. Just evaluate keys in scalar context, which efficiently returns the number of keys, rather than the list of keys. After that, you'll find each has been reset as desired.

Here's a sample illustration:

use strict; use warnings; my %hash = ( Who => 'Me', What => 'Person', How => 'Conception', When => '35 years ago', Where => 'I dont want to know', Why => 'Irrelevant' ); while ( my ( $key, $value ) = each %hash ) { print "$key => $value\n"; scalar keys %hash; }

If you run that you'll now find yourself in a neverending loop, since each gets reset each time through the while loop. In this illustration, the use of the pseudo-function scalar is unnecessary. As long as keys isn't being evaluated in list context, Perl is smart enough to not go to the work of creating a list of keys that just gets thrown away.

Hope this helps...

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: Reset while loop to beginning of hash when using 'each'
by seaver (Pilgrim) on Sep 26, 2003 at 17:24 UTC
    Fantastic, it hadnt occured to me that the iteration was in the 'each' function. Great answer too, so easy to read!

    Cheers
    Sam

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://294288]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.