perl@1983 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to compare below two variables using regex:
$var1 = "This (is)- my first string"; $var2 = "This (is)- my first string";
If did something like this:
if ($var1 =~ /$var2/) { print "Matched"; } else { print "Did not match"; }
Surprisingly, above test is always producing "Did not match". Am I missing anything in the comparison? Thanks.

Replies are listed 'Best First'.
Re: RegEx Comparison
by davido (Cardinal) on May 03, 2011 at 00:25 UTC

    This (is)- my first string, is not a regular expression. It's just a string. But when you wrap it in an m// operator, you're telling Perl it's a regular expression. Within regular expressions, parenthesis have meaning. In fact just about every printable non-word character on your keyboard has meaning to the regex engine. So let's look at what you're asking Perl to validate:

    use 5.012_002; use strict; use warnings; use YAPE::Regex::Explain; my $var1 = "This (is)- my first string"; my $var2 = "This (is)- my first string"; say YAPE::Regex::Explain->new($var2)->explain();

    And the output:

    The regular expression: (?-imsx:This (is)- my first string) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- This 'This ' ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- is 'is' ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- - my first string '- my first string' ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------

    So you're asking Perl if "This (is)- my first string" matches "This is- my first string" (the parens are getting interpreted as 'something else' within the regular expression. You have a few options. One is to pass your second string through quotemeta. Another is to simply do a direct comparison using 'eq', rather than a regexp match.


    Dave

Re: RegEx Comparison
by toolic (Bishop) on May 02, 2011 at 23:36 UTC
Re: RegEx Comparison
by educated_foo (Vicar) on May 02, 2011 at 23:33 UTC
    If you want to test if they are the same, then you're looking for the eq operator.