The below is one way:
Keep things simple.
Output of below is: term 'alpha' detected on input line 4
The code below is very efficient and runs fast.
#!usr/bin/perl -w use strict; while (<DATA>) { if(/\balpha\b/) { print "term 'alpha' detected on input line $.\n"; next; } .. do something here... .. sometimes better than elsif() } __DATA__ beta beta beta alpha # this line appears only once in the whole file beta beta beta
if you have a lot of conditions, then perhaps something like this is appropriate:
while ( <FILE> ) { if ( /alpha/ ) { .... next; } if (/beta/) { .... next; } #here is the default code... }
One of the reasons to do it that way is so that all of the conditions can be interchanged with one another. If you have an if(..)elsif(..)else(..) conditional, this hinders the ability to change the order of the conditions. At the end of the day, that approach will result in more complex code and limit the ability to re-order the code's priority of matching - don't do it. At least for number of "if" statements of about 5-6.

Update: Well this is one of those situations where there just isn't a "one size fits all" solution. I tend to prefer coding with several sequential if{..} statements so that all of them are "equal". This whole coding style discussion can set off something that will last until a gallon of gas falls back to $1.60.


In reply to Re: A way to avoid repeated conditional loops by Marshall
in thread A way to avoid repeated conditional loops by Deus Ex

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.