http://qs321.pair.com?node_id=1214097


in reply to Can I check if a loop's scope is entered for the first time?

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.

  • Comment on Re: Can I check if a loop's scope is entered for the first time? (functional approach)
  • Select or Download Code