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:

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 21: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