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":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.