Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Doing "it" only once

by QM (Parson)
on Sep 21, 2005 at 23:05 UTC ( [id://493994]=note: print w/replies, xml ) Need Help??


in reply to Doing "it" only once

I might as well wade into the fray, and show TIMTOWTDI in Perl5...

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
Once there is no more code that would pass the conditionals, the loop exits.

(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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://493994]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-20 04:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found