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

Dear all? I am struggling to find a way to remove an UNC path contained in a scalar from another scalar.
$cache = "\\myserver\cache\dir";
$path = "\\myserver\cache\dir\2003\Feb\file.tmp";
to make this path relative: ie.
$path =~ s/$cache//g;

Doesn't work. I'm presuming because there are escape characters in the $cache scalar. Is there a way of forcing escape of a string even though it is contained in a scalar.


Any help is much, much, muchly appreciated.</P

yours in awe...

A.
  • Comment on Susbstituting strings with escape characters.

Replies are listed 'Best First'.
Re: Susbstituting strings with escape characters.
by bronto (Priest) on Feb 12, 2003 at 14:02 UTC
    $path =~ s/\Q$cache\E//g;

    Ciao!
    --bronto


    The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
    --John M. Dlugosz
Re: Susbstituting strings with escape characters.
by Hofmator (Curate) on Feb 12, 2003 at 14:00 UTC
Re: Susbstituting strings with escape characters.
by fruiture (Curate) on Feb 12, 2003 at 14:05 UTC

    You should have a look at perlop about interpolation: The backslash is a tricky character, especially in double quotes. If you had enabled warnings, the invalid escapes \c and \d would have occured to you already.

    my $cache = q{\\\\myserver\cache\dir}; my $path = q{\\\\myserver\cache\dir\2003\Feb\file.tmp};

    Inside q// (aka 'single quotes') the backslash only escapes itself and the string delimiter.

    The next problem is that when interpreted as regular expression, the backslash has again different meanings, see perlre, here \d is a meaningful sequence. You need quotemeta() or simply the \Q \E escapes inside the RE:

    s/\Q$cache\E//

    And btw.: The /g does not make sense here.

    --
    http://fruiture.de