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 | |
|
Re^2: Doing "it" only once
by jdporter (Paladin) on Sep 21, 2005 at 16:16 UTC |