PUCKERING has asked for the wisdom of the Perl Monks concerning the following question:
I've tried a closure, and a class (with a next method), and even the Iterator module. No joy.
Here's an example, cribbed from the Iterator POD:
That prints 3, when it should print lines containing 3, 4 and 5.use Iterator; sub irange_limited { my ($start, $end) = @_; return Iterator->new ( sub { Iterator::is_done() if $start > $end; return $start++; } ); } my $it = irange_limited(3, 5); foreach ( $it->value ) {say $_ }
Even the venerable High Order Perl book, which has an entire chapter devoted to iterators and some fine examples, fails to mention anything about using them in foreach -- or not being able to. And while foreach is used within the implementation of some examples, they use cases all use while(). This leads me to think there may be some fundamental reason why it cannot work.
Your wisdom and enlightenment, as always, would be much appreciated.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How can I create an iterator that works inside foreach() (updated)
by AnomalousMonk (Archbishop) on Nov 05, 2022 at 00:24 UTC | |
by PUCKERING (Sexton) on Nov 05, 2022 at 02:24 UTC | |
by hv (Prior) on Nov 05, 2022 at 04:04 UTC | |
by AnomalousMonk (Archbishop) on Nov 05, 2022 at 03:27 UTC | |
by AnomalousMonk (Archbishop) on Nov 05, 2022 at 03:55 UTC | |
Re: How can I create an iterator that works inside foreach()
by hv (Prior) on Nov 05, 2022 at 00:14 UTC | |
Re: How can I create an iterator that works inside foreach()
by jwkrahn (Abbot) on Nov 04, 2022 at 22:10 UTC | |
Re: How can I create an iterator that works inside foreach()
by haukex (Archbishop) on Nov 06, 2022 at 08:12 UTC |