This problem occurs so much it should be considered a FAQ. If you want to use a variable as a regex, you must remember that it is what's in the string that matters, not what you typed to produce that string. The string contains / should contain what you would write literally in the regex. So, wat do you expect to see if your do:
my $match = "\\well"; print $match;
? Well: it prints
\well
So doing
my $match = "\\well"; $text =~ s/$match//;
is, more or less (apart from the fact that the regex can be altered at runtime), equivalent to writing:
$text =~ s/\well//;
and /\w/ can match any letter, which is the effect you see: match a word character followed by "ell". For your string this deletes the word "well".

Conclusion: if you want to match a literal backslash, the regex/string should contain two backslashes, so the source code to produce the string should contain 4:

my $match = "\\\\well"; $text =~ s/$match//;
One way around this is to use qr//:
my $match = qr/\\well/; $text =~ s/$match//;
In this case, what you type is what you get — including any present or missing modifiers.

p.s. If you load the pattern(s) for a regex from a text file, you won't have this problem, as what is in the file is what will be in the pattern.


In reply to Re: using a scalar in a regex with backslashes by bart
in thread using a scalar in a regex with backslashes by Anonymous Monk

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.