Learned Monks,

I have a Perl array that I've filled with interesting things I want to look for within a file. I can't figure out how to perform this search more elegantly than with a loop that looks for each item in turn with brute force:

#!/usr/local/bin/perl -w use strict; my @names = ("john", "paul", "george", "ringo"); while(<STDIN>) { chomp; my $hit = 0; foreach my $name (@names) { if (m/^static\s+\w+\s+(${name})\W.*/) { $hit = $1; last; } } if ($hit) { print "Beatle method \"$hit\" found on this line: $_\n"; } else { print "No Beatle method found on this line: $_\n"; } }
If my array always had four members, I could optimize the code above to something like this:
while(<STDIN>) { chomp; if (m/^static\s+\w+\s+($names[0]|$names[1]|$names[2])\W.*/) { print "Beatle method \"$1\" found on this line: $_\n"; } else { print "No Beatle method found on this line: $_\n"; } }
The array can have one or many entries however. Ideally I'd like a one-liner like above, but for any size array:
# Note that this line isn't supposed to compile... if (m/^static\s+\w+\s+(???@names???)\W.*/) {
FYI... Data like this:
static int lars(...); static bool george(...); static int thom(...);
Should produce output like this:
No Beatle method found on this line: static int lars(...); Beatle method "george" found on this line: static bool george(...); No Beatle method found on this line: static int thom(...);
Thanks for your help!

In reply to RegExp to Search All Array Members? by shoness

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.