Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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.

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

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2023-04-01 00:43 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (77 votes). Check out past polls.