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