Once the match has been made, why must every subsequent line in the file be tested? I have also desired this ability in long tight running loops when performance was a concern and tried to figure out a way to make it work. I came up with the following inelegant code:while ( <FH> ) { next if $_ eq 'foo'; # Where foo can only appear once in the file print; }
Once the condition has been met, the code dynamically changes to no longer check for the condition. Keep in mind, to get this luxury I am now paying for the overhead of dereferencing and invoking a sub each time to get this "performance" benefit.#!/usr/bin/perl use strict; use warnings; do_something(5); sub do_something { my $target = shift; my $block; my $block2 = sub { print "No need to check $_ against $target anymore\n"; }; my $block1 = sub { if ( $_ == $target ) { print "Skipping $target\n"; $block = $block2; } else { print "$_ is not $target\n"; } }; $block = $block1; for ( 1 .. 9 ) { $block->(); } }
I was wondering what your thoughts on this are? If you think of running code as a work flow and each piece of functionality a widget then what we are talking about is a special kind of widget that can replace another widget while the work flow is running. Would building this functionality in the Perl 6 core be of great benefit? Obviously providing the functionality would open the door for other applications then just the "run once" feature. If this ability existed with negligible costs - what other things could you think of to do with it?
Cheers - L~R
Update: I removed some irrelevant pieces of the code which were leftover from my trial and error attempts
In reply to Doing "it" only once by Limbic~Region
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |