Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

(dkubb) Re: (2) Returning _which_ pattern matched...?

by dkubb (Deacon)
on Aug 03, 2001 at 20:33 UTC ( [id://102033]=note: print w/replies, xml ) Need Help??


in reply to Returning _which_ pattern matched...?

Remember to use quotemeta or \Q and \E on any variables you are going to use inside a regex. If you forget to, and any special regex meta-characters exist in your variables, your program can do anything between match unwanted strings to completely die'ing.

I see this problem in alot of code where the program "builds" a regex. Bugs caused by forgetting to do this can go undetected for a long time until a "+", "|" or a ")" occurs somewhere in the incoming data. (assuming the data being searched through is not hard coded into the script, and thus it's content controlled by the programmer - as it's often not in the real world)

Here's some sample code to illustrate the use of quotemeta in solving your problem:

#!/usr/bin/perl -w use strict; use constant STRING => 'clintonesque'; use constant TO_MATCH => qw( Clinton Bush Reagan ); my $regex = join '|', map { quotemeta } TO_MATCH; my ($first_match) = STRING =~ /($regex)/i; print $first_match;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-20 02:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found