Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by hv (Prior)
on Nov 05, 2022 at 04:04 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-04-20 08:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found