in reply to Doing "it" only once

How is what you want to do different from the last keyword? Or is your goal to make multiple such checks "optimally efficient"?

while (<DATA>) { if (/foo/) { print "Found 'foo'\n"; }; if (/bar/) { print "Found 'bar'\n"; }; if (/baz/) { print "Found 'baz'\n"; }; print "Unknown line: $_"; }; __DATA__ foozle bazzle barren

If you want to reduce the loop size without paying a high syntactical tax I would use the following:

my @items =( sub { /foo/ and do { print "Found 'foo'\n"; }}, sub { /bar/ and do { print "Found 'bar'\n"; }}, sub { /baz/ and do { print "Found 'baz'\n"; }}, sub { print "Unknown line: $_"; undef }, ); my @current = @items; while (defined (my $line = <DATA>)) { my @remaining = @current; @current = (); local $_ = $line; CODE: while (my $c = shift @remaining) { if ($c->()) { push @current, @remaining; last # CODE } else { push @current, $c; }; }; }; __DATA__ foozle --- #1 bazzle --- #2 barren --- #3

The driving loop should likely be hidden away in some module. But the whole thing is suspiciously close to Switch.pm anyway, and I (without benchmarks) doubt that an optimization like this will buy much unless the single tests are very expensive, as the subroutine calls are "expensive" too and the loop and anonymous subroutines make things harder to debug. And you need to make sure that all match routines return a true value when they actually matched

Replies are listed 'Best First'.
Re^2: Doing "it" only once
by Limbic~Region (Chancellor) on Sep 21, 2005 at 15:42 UTC
    Corion,
    This specific case relates more to the next keyword than to last. The idea is that once a particular piece of code has been invoked, it magically disapears.
    for ( 1 .. 100 ) { next if $_ == 50; print "$_\n"; }
    Becomes functionally equivalent to print "$_\n" for 1 .. 49, 51 .. 100;. The meditation isn't about solving for specific cases but having the ability to dynamically change the running code and what would you do with it if it were cheap.

    It really isn't like a source filter because you want the code to first be there and then go away while the code is running. I am already pretty sure that there is no way in the existing language to get this optimization without paying more for it then you get out. That's not what the medidation is about though.

    Cheers - L~R

Re^2: Doing "it" only once
by jdporter (Paladin) on Sep 21, 2005 at 16:16 UTC
    It quickly becomes apparent that a generic solution to the general problem is a state machine, and that such a generic solution is (or could be) an interpreter of a regular language. (This is taught in (approximately) CS 440, though the principles are introduced earlier than that.)