shoness has asked for the wisdom of the Perl Monks concerning the following question:
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(...);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: RegExp to Search All Array Members?
by RMGir (Prior) on Jun 19, 2007 at 09:34 UTC | |
by moritz (Cardinal) on Jun 19, 2007 at 10:26 UTC | |
by ff (Hermit) on Jun 19, 2007 at 13:19 UTC | |
by Aceflex (Initiate) on Jan 03, 2012 at 23:33 UTC | |
by Anonymous Monk on Aug 16, 2012 at 20:42 UTC | |
by johngg (Canon) on Jun 19, 2007 at 13:33 UTC | |
|
Re: RegExp to Search All Array Members?
by duff (Parson) on Jun 19, 2007 at 12:26 UTC |