Perl regex ignoring [] meta characters

Hi Experts,

I'm having trouble with a Perl regex which tests whether one string is contained in another.  In real life, the data comes from a file and a database, but the code snippet below demonstrates the issue:

    $var1 = 'A [B:2013-03] C';
    $var2 = '[B:2013-03]';
    print "Match!\n" if $var1 =~ /$var2/;

The above gives this error message:
Invalid [] range "3-0" in regex; marked by <-- HERE in m/[B:2013-0 <-- HERE 3]/ at ./sub.pl line 3.

How can I best avoid this problem and get the match to work by ignoring the meta characters?

I know I could escape the [] in $var2, like this:
    $var2 = '\[B:2013-03\]';
but I'm hoping there's a cleaner way.

Thanks.
tel2
LVL 12
tel2Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
ozoConnect With a Mentor Commented:
$var1 =~ /\Q$var2\E/
or
index($var1,$var2) >= 0
0
 
tel2Author Commented:
Well said, ozo.  TIMTOWTDI.

In your first solution, I guess I could omit the '\E' in this case.

Thank you.  That's just what I was after.
tel2
0
 
ozoConnect With a Mentor Commented:
Or, if you are testing many $var1's with the same $var2, you may want to first do
$var2 = qr/\Q$var2/;
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
tel2Author Commented:
For performance, ozo?
0
 
ozoCommented:
yes
0
 
tel2Author Commented:
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.