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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.