Between the two approaches you mentioned, I would be extremely surprised if the hash did not turn out to be more efficient, as it doesn't have to step through a list of thousands of elsifs. It also has the advantage of taking constant time regardless of whether the string is found or not, rather than being very quick if the string is at the start of the elsif chain and being slower for a non-matching string, which would have to individually check every item in the list before it can be known that the string isn't there.

More importantly, though, the hash approach is much more readable than an endless list of elsifs, and it also opens up the possibility of storing your list of items to match against in a config file or a database (since a hash's contents are just data, not code) which will make for easier long-term maintenance.

BTW, the syntax you probably want for checking whether a hash key exists is exists($hash{$string}), not defined (which will return false if the key is there but has no value).


In reply to Re: Hash versus chain of elsifs by dsheroh
in thread Hash versus chain of elsifs by mldvx4

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.