tent8f has asked for the wisdom of the Perl Monks concerning the following question:

$filename_a = "c:\\abc.log"; $filename_b = "c:\\abc.log"; print "Are they equal ? : "; print $filename_a eq $filename_b ; # output is 1 print "\n"; print "Do they match ? : "; print $filename_a =~ /$filename_b/ ; # output is blank
if I remove the \\ from each string then output for both is 1. help or valium needed

Replies are listed 'Best First'.
Re: NT paths and regexp (\Q)
by tye (Sage) on Sep 12, 2003 at 17:05 UTC

    That is because you wrote the wrong code:

    print "Do they match ? : "; print $filename_a =~ /\Q$filename_b\E/ ; # output is 1

    Always remember:

    /$regex/ /\Q$string\E/

    If you use a variable as part of a regex, Perl needs to know if you want to interpret that variable as a string or as a regex. The default is to interpret it as a regex. If you want to use a string (from a variable) in a regex, then you need to tell Perl that by using \Q (or quotemeta, though this is can't be used as easily directly in the regex).

                    - tye
Re: NT paths and regexp
by Abigail-II (Bishop) on Sep 12, 2003 at 14:43 UTC
    That's because "\\a" still has a backslash, and backslashes followed by a letter may have a special meaning for the regex. /\a/ matches a bell character (^G), and not a backslash followed by an a.

    In general, $str =~ /$str/ is often not a match due to the special meaning of characters in $str.

    Abigail

Re: NT paths and regexp
by tcf22 (Priest) on Sep 12, 2003 at 14:43 UTC
    The string is being interpolated again, so you need \ x4.
    $filename_b = "c:\\\\abc.log";
    but then the eq won't work.
    You could also use the magic of qr//
    $filename_a = "c:\\abc.log"; $filename_b = "c:\\abc.log"; $filename_b_re = qr/c:\\abc.log/; print "Are they equal ? : "; print $filename_a eq $filename_b ; # output is 1 print "\n"; print "Do they match ? : "; print $filename_a =~ /$filename_b_re/ ; # output is 1

    Another option(prefered, at least by me) is to use / instead of \\
    $filename_a = "c:/abc.log"; $filename_b = "c:/abc.log";

    - Tom

      You could also use the magic of qr//

      But only if you cut-and-paste the string, not if you do:

      $filename_b_re = qr /$filename_b/;

      It's not the magic of qr that makes it work, it's the magic of cut-and-paste. This will work too:

      print $filename_a =~ /c:\\abc.log/; # output is 1

      Abigail

        I know, I was giving some options.
        Like i said, the way I prefer to do it is using c:/abc.log. NT sees it as a valid path, and you don't have to worry about escaping anything.

        - Tom