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:
If my array always had four members, I could optimize the code above to something like this:#!/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"; } }
The array can have one or many entries however. Ideally I'd like a one-liner like above, but for any size array: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"; } }
# Note that this line isn't supposed to compile... if (m/^static\s+\w+\s+(???@names???)\W.*/) {
Should produce output like this:static int lars(...); static bool george(...); static int thom(...);
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(...);
In reply to RegExp to Search All Array Members? by shoness
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |