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


In reply to Re: Reset while loop to beginning of hash when using 'each' by davido
in thread Reset while loop to beginning of hash when using 'each' by seaver

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.