Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Answer: How do I escape metacharacters in a user-defined string?

( #21600=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I escape metacharacters in a user-defined string? contributed by Ovid

This is an easy mistake to make. I've made it myself. Notice that in $bit, you have parentheses '()' and a plus '+'. What your regex is doing is trying to find one or more fours followed by one five. It then, if successful, would capture this to $1.

The easiest way to deal with the is to use the "quote" metacharacters (\Q and \E) in the regex.

$formula = $bit = '(4+5)'; if( $formula =~ /\Q$bit\E/ ) { print "yeah\n"; } else { print "Oh no!\n"; }
This will work as you expect. However, you'll have to be careful. Here's a warning from perlop:
    You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be inserted. You'll need to write something like m/\Quser\E\@\Qhost/.

Comment on Answer: How do I escape metacharacters in a user-defined string?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (12)
As of 2014-09-19 18:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (144 votes), past polls