Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^3: How can I create an iterator that works inside foreach() (updated)

by hv (Prior)
on Nov 05, 2022 at 04:04 UTC ( #11147983=note: print w/replies, xml ) Need Help??

in reply to Re^2: How can I create an iterator that works inside foreach() (updated)
in thread How can I create an iterator that works inside foreach()

In the context of that website, it's possible that the intent is something more like the C-style for loop, in which case something like the following might be a better fit:

sub range { my($start, $end) = @_; return sub { return undef if $start > $end; return $start++; }; } my $it = range(3, 5); for (my $value; $value = $it->(); ) { say $value }

(But actual idiomatic perl would use a while loop here.)

If the intent is to handle a list-style for loop, the "iterator" can be made much simpler by handling just that case, which I think is similar to the Ruby solution shown:

sub list_range { my($start, $end) = @_; return sub { $start .. $end }; } my $lit = list_range(3, 5); for ($lit->()) { say $_ }

In the current example perl code at the link, the "_upto" function is not needed, it can simply be replaced with "sub", as in my examples above: the sub keyword in this context yields an anonymous subroutine reference from the block that follows it, and Higher Order Perl should be telling you all about that. The comment "To work in a foreach each loop, inner sub upto must be predeclared to take an anonymous sub argument" is wrong - if we have a subroutine reference, $it->() will happily invoke it, whether it's in a for loop or not.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11147983]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (2)
As of 2023-03-29 22:02 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (73 votes). Check out past polls.