Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
FWIW this "works" somehow, but lacks the elegance of the "while solution" approach...

Please note that now, one can have more than just one loop var, like a "pointy block" in Perl6.

The cheat is that $a has to be global here to work under strict.*

Using my $a wouldn't work, because the scope only starts after the statements semicolon, and the body-sub is defined before.

use strict; use warnings; use Data::Dump qw/pp dd/; sub iter (&$;@) { my $gen = shift; my $body = pop; for (my $it = $gen->(@_) ; $it->(@_); ) { $body->(); } } for my $limit (reverse 1..5) { iter { countdown($limit) } $a => sub { print "$a: "; }; print "\n"; } sub countdown{ my $val = shift; my $it = sub { if ($val--) { $_[0]=$val; return 1; } return; # stop iteration }; return $it; }
4: 3: 2: 1: 0: 3: 2: 1: 0: 2: 1: 0: 1: 0: 0:

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Wikisyntax for the Monastery

update

Renamed loop to iter ... the loop construct in Perl6 is another beast, and wanted to avoid confusion.

*) remember $a and $b are global to allow sort to work.


In reply to Re: Can I check if a loop's scope is entered for the first time? (functional approach) by LanX
in thread Can I check if a loop's scope is entered for the first time? by LanX

Title:
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2022-12-09 15:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?