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


In reply to Re: Doing "it" only once by Corion
in thread Doing "it" only once by Limbic~Region

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.