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;

In reply to (dkubb) Re: (2) Returning _which_ pattern matched...? by dkubb
in thread Returning _which_ pattern matched...? by Boudicca

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.