perlquestion
LanX
For an iterator to work in Perl one needs to initialize it properly <P>
<c>
use strict;
use warnings;
use Data::Dump qw/pp dd/;
for my $limit (reverse 1..5) {
for ( my $iter = countdown($limit); $iter->(my $a) ; ) {
print "$a: ";
}
print "\n";
}
sub countdown{
my $val = shift;
my $iter = sub {
if ($val--) {
$_[0]=$val;
return 1;
}
return; # stop iteration
};
return $iter;
}
</c>
<c>
4: 3: 2: 1: 0:
3: 2: 1: 0:
2: 1: 0:
1: 0:
0:
</c><P>
(I used c-style for here for clarity*)<P>
But I'd rather like to stay DRY and to write something like
<b>
<c>
while ( countdown $limit => my $a ) {
....
}
</c>
</b><P>
Where countdown can elaborate if the loop is (re)entered and does the init step automatically.<P>
NB: Other languages have this feature for so called iterator objects.<P>
I'm wondering if this could be tricked into Perl without XS wizardy °...<P>
<H5> Approaches ...</H5>
<UL>
<LI> I tried <C>%^H</C> , but this seems to be a compile time effect only.
<LI> Blessing a DESTROY method to <C>\$a</C> doesn't help, because it's triggered for all iterations not only the first.
<LI> I was thinking to use [mod://PadWalker] to inject a var with a DESTROY hook into <C>closed_over</C> , but I doubt this has a chance to work.
<LI> UPDATE: Well with [METAMOD://Keyword::Simple] I could define a new <C>loop</C> keyword which expands into <C>for(;;;)</C>
<LI> UPDATE: there is some magic connected to the diamond operator <C><$obj></C> which can be overloaded, but you can't use it with functions because the syntax is convoluted with file-glob.
</UL>
IDEAS?
<div class="pmsig"><div class="pmsig-708738">
<p>Cheers Rolf<br>
<sub>(addicted to the Perl Programming Language and [http://i.dailymail.co.uk/i/pix/2014/07/14/article-2690897-1F9F6C0E00000578-463_964x629.jpg|☆☆☆☆] :)
<br> <i> [id://1153804|Wikisyntax for the Monastery]</i>
</sub> <P>
</div></div><P>
*) please note that <C>while(CODE){}</C> and <C>for(;CODE;){}</C> have the same effect.<P>
°) many issues could be solved like this...<P>
<H5> update</H5><P>
The countdown iterator was used for demonstration only, I now plenty of ways to countdown. Iterators are a general issue. <!-- Wiki2Monks {"version":1.1416} -->