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

Re: grep : partial and/or exact match

by chipmunk (Parson)
on Nov 30, 2001 at 07:57 UTC ( #128542=note: print w/replies, xml ) Need Help??


in reply to grep : partial and/or exact match

Yup, you could do it with grep, by reversing the match. Match the restricted word against the input word:
my @restricted_words = qw ( funk shucks crud ); if (grep $word =~ /$_/, @restricted_words) { print "wash your mouth out!\n"; } else { print "Such a nice boy\n"; }
That code will be very slow, however, because it's recompiling the regex each time. Although you could avoid that problem with qr//, it would be simpler to skip grep and just make one big regex:
my @restricted_words = qw ( funk shucks crud ); my $restricted_re = '(?:' . join('|', @restricted_words) . ')'; $restricted_re = qr/$restricted_re/; if ($word =~ $restricted_re) { print "wash your mouth out!\n"; } else { print "Such a nice boy\n"; }
This approach will give you both speed and flexibility. Enjoy!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2020-01-26 21:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?