[comp.lang.perl] Using 'grep

merlyn@iwarp.intel.com (Randal Schwartz) (01/23/90)

In article <6865@jpl-devvax.JPL.NASA.GOV>, lwall@jpl-devvax (Larry Wall) writes:
| @PATTERNS = ('foo','bar','whatever');
| 
| $prog = "while (<>) { study;\n";
| 
| foreach $pat (@PATTERNS) {
|     $prog .= "print if /$pat/;\n";
| }
| 
| $prog .= "}\n";
| 
| eval $prog;

Of course, with your wonderful new "grep" operator, which I have been
using as the "apply" operator, you could have done it like this:

############################## snip
@PATTERNS = ('foo','bar','whatever');

$prog = "while (<>) { study;\n" .
	join("\n", grep(s#(.*)#print if /\1/;#,
			grep(s#(\W)#\\\1#g || 1, @PATTERNS))) .
	"\n}\n";

eval $prog;
############################## snip

which automatically quotes any metachars in the pattern strings to
make them normal (stolen from your one-and-only manpage).  All in one
statement, too, so it's pretty darn fast.

Just another Perl hacker (and soon-to-be-published author),
-- 
/== Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ====\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III  |
| merlyn@iwarp.intel.com ...!uunet!iwarp.intel.com!merlyn                |
\== Cute Quote: "Welcome to Oregon... Home of the California Raisins!" ==/