Here's one way. The iterator in this example is very simple: it has no way to reset or reinitialize once it is exhausted, and it will only reach exhaustion in a while-loop or equivalent (update: i.e., in scalar-context invocation).

c:\@Work\Perl>perl use strict; use warnings; # use Data::Dump qw(dd); # for debug sub Iterator (&) { return $_[0]; } # syntactic sugar per mjd (Dominus +) sub irange_limited { my ($start, $end) = @_; return Iterator { return if $start > $end; return wantarray ? $start .. $end : $start++; }; } my $iter = irange_limited(3, 5); for my $n ($iter->()) { print "for loop: $n \n"; } while (my $n = $iter->()) { print "while loop: $n \n"; } ^Z for loop: 3 for loop: 4 for loop: 5 while loop: 3 while loop: 4 while loop: 5

Update: Here's a slightly more sophisticated iterator. It always returns the full range when invoked in list context, and it will automatically reset when exhausted upon invocation in scalar context. Note, however, that list and scalar context invocations are independent of each other!

sub irange_limited { my ($start, $end) = @_; my $n = $start; return Iterator { return wantarray ? $start .. $end : $n > $end ? ($n = $start, ()) : $n++ ; }; }
(Update: Also note that this solution has a semipredicate problem. The range -1, 1 will result in a value of 0 (false) that will terminate a while-loop prematurely. A further defined test is needed in the while-loop condition because undef (also false) flags iterator exhaustion. (Update: There are also other solutions to this problem :))


Give a man a fish:  <%-{-{-{-<


In reply to Re: How can I create an iterator that works inside foreach() (updated) by AnomalousMonk
in thread How can I create an iterator that works inside foreach() by PUCKERING

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.