Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Possible Match Problem

by Marshall (Prior)
on Jan 18, 2012 at 23:39 UTC ( #948649=note: print w/ replies, xml ) Need Help??


in reply to Possible Match Problem

#!/usr/bin/perl -w use strict; my $str1 = "Hi("; my $str2 = "hi"; if ($str2 =~ /\Q$str1\E/) #\Q...\E means like qr #don't interpret characters #like '(' within $str1 #use them verbatim { print "Match: Yes\n"; } else { print "Match: No\n"; } #prints Match: No $str2 = "hI("; if ($str2 =~ /\Q$str1\E/i) #/i means case insensitive { print "Match: Yes\n"; } else { print "Match: No\n"; } #prints Match: Yes
Basically if you want to match upon string where one or more characters would mean something to a Perl regex, you need to say that: "I don't want these special characters to count, i.e. mean something in a regex sense" - otherwise when Perl interpolates that string, those characters "will count". There are a couple of ways to say "please use all these characters verbatim", I showed one of these. qr is another.


Comment on Re: Possible Match Problem
Download Code
Re^2: Possible Match Problem
by AnomalousMonk (Monsignor) on Jan 19, 2012 at 06:05 UTC
    ... a couple of ways to ... use all these characters verbatim ... qr is another.

    In no way will  qr use any metacharacters verbatim unless specifically 'told' to do so, e.g., by a  \Q ... \E escape sequence.

    >perl -wMstrict -le "my $s = 'hi('; my $rx = qr{$s}; " Unmatched ( in regex; marked by <-- HERE in m/hi( <-- HERE / at ...

    Update: See  qr in the Regexp Quote Like Operators section of perlop, also see section on 'escape sequences' (for \Q) in Quote and Quote like Operators, also in perlop.

      correct. qr is better used for other things. my example was with \Q...\E, so I'll leave it at that.
        if ($str2 =~ /\Q$str1\E/) #\Q...\E means like qr #don't interpret characters #like '(' within $str1 #use them verbatim

        To avoid misunderstanding, you might also consider removing "like qr" from the foregoing comment, or possibly changing to something like "means, as when used in qr, to avoid interpreting characters like ...".

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2014-07-12 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (240 votes), past polls