Using an joined pattern like "foo|bar|baz" can be quite inefficient depending on the patterns, since the regex engine can't find "anchored substrings" and can't guess where the match is. So here's some more or less attractive alternatives.

The first one is the one I prefer if I don't know anything about the string nor patterns since it doesn't do more matches than necessary (comparing with the other two) and need it as an expression. It utilizes an "inline sub" as I call them, I don't know if there's any other name for them. It's a closure and why I use a subroutine for this is that I want to use it as an expression and be able to jump out of it. So &{sub { ... }} is like do { ... } except you can use return in it. (Note the subtle difference between &{sub { ... }} and sub { ... }->().) I admit it is a bit ugly, but at the same time I like it.

if (&{sub { $bigstring =~ /$_/ and return 1 for @array }}) { ...; }

Of course, a less hacky way could be

my $matched; $matched = $bigstring =~ /$_/ and last for @array; if ($matched) { ...; }

which I prefer even more if I don't need it as an expression.

This next one counts the matches, which is inefficient if you just want one match.

if (grep $_, map $bigstring =~ /$_/, @array) { ...; }

This one below does essentially the same, but is less memory hungry for big lists.

if (map $bigstring =~ /$_/ ? 1 : (), @array) { ...; }

I'm not sure I really helped here...
ihb


In reply to Re: matching elements in a list in a logical OR fashion by ihb
in thread matching elements in a list in a logical OR fashion by Anonymous Monk

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.