in reply to Doing "it" only once
How about a function table where the entries remove themselves once they're no longer needed?
#!/your/perl/here # demo self-modifying function table use strict; use warnings; sub gen_sub { my ($match, $target) = @_; my $count = 0; return sub { my ($item, $function, $num) = @_; print "<$match> eq <$item>?\n"; if ($item eq $match) { $count++; print "found $match, count=$count, target=$target\n"; if ($count >= $target) { delete( $function->{$num} ); print "no more $match\n"; } return(1,$function); } return(0,$function); } # end sub } # gen_sub # construct function table my $function = {}; my $limit = 1; my $order = 0; foreach my $sub ('foo', 'bar', 'baz') { $function->{$order++} = { 'NAME' => $sub, 'CODE' => gen_sub($sub,$limit++) }; } my $hit; PASS: while (keys %{$function}) { while (<DATA>) { chomp; foreach my $num (sort {$a<=>$b} keys %{$function}) { ($hit,$function) = $function->{$num}{CODE}($_,$function,$n +um); next PASS if $hit; } } } exit; __DATA__ junk foo bar baz foo bar baz foo bar baz more junk __OUTPUT__ <foo> eq <junk>? <bar> eq <junk>? <baz> eq <junk>? <foo> eq <foo>? found foo, count=1, target=1 no more foo <bar> eq <bar>? found bar, count=1, target=2 <bar> eq <baz>? <baz> eq <baz>? found baz, count=1, target=3 <bar> eq <foo>? <baz> eq <foo>? <bar> eq <bar>? found bar, count=2, target=2 no more bar <baz> eq <baz>? found baz, count=2, target=3 <baz> eq <foo>? <baz> eq <bar>? <baz> eq <baz>? found baz, count=3, target=3 no more baz
(BTW, what keeps the world from imploding when the current sub is deleted from the function hash? There must be a referent lying around somewhere until the sub exits, right?)
-QM
--
Quantum Mechanics: The dreams stuff is made of
|
|---|