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.