Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Reverse grep?

by chipmunk (Parson)
on Mar 02, 2002 at 17:23 UTC ( #148853=note: print w/ replies, xml ) Need Help??


in reply to Reverse grep?

By "reverse grep", I take it that you mean you want to loop over a list of regexes with one string, rather than loop over a list of strings with one regex. As far as Perl is concerned, these are the same.

Your difficulty comes from thinking of Perl's grep as being the same as the command line grep. This is not the case. In Perl's grep, the conditional is not necessarily a pattern match; it is any arbitrary Perl expression. For example, you could do something like this: @results = grep { $_ & 1 } (1 .. 10)
to get a list of odd numbers between 1 and 10.

Thus, you can do any filtering you want with grep, with the proper conditional expression. What you're looking for could be written something like this (with some regexes I made up):

my $url = 'http://www.perlmonks.org/'; my @regexes = ('/private(?:/|$)', 'python'); if (grep { $url =~ $_ } @regexes) { # handle bad URL } else { # handle good URL }
As suggested in another response, you'd probably want to precompile the regexes with qr// for efficiency.


Comment on Re: Reverse grep?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://148853]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2014-11-25 00:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (148 votes), past polls