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

I'm trying to remove for example 'C:\temp' from Windows paths, and this works (prints 'new path: \dest'):

my $path = "C:\\temp\\dest"; $path =~ s/C:\\temp//i; print "new path: $path\n";

But I need to use a variable, and this doesn't work (prints 'new path: C:\temp\dest'):

my $srcDir = "C:\\temp"; my $path = "C:\\temp\\dest"; $path =~ s/$srcDir//i; print "new path: $path\n";

And it dies on this line, but I don't know why (prints 'Died at sub.pl line 4.'):

$path =~ s/$srcDir//i or die;

Another example of a substitution using variables that does not work (prints 'Died at sub2.pl line 5.'):

my $srcDir = "C:\\temp"; my $destDir = "C:\\temp2"; my $path = "C:\\temp\\dest"; $path =~ s/$srcDir/$destDir/i or die; print "new path: $path\n";

Replies are listed 'Best First'.
Re: Windows directory path variable binding operator substitutions
by moritz (Cardinal) on Mar 17, 2008 at 16:54 UTC
    $path is interepreted as a regex, which means that it tries to match \t, which is a tab character.
    $path =~ s/\Q$path\E//i;
    should work. See also quotemeta.
Re: Windows directory path variable binding operator substitutions
by kyle (Abbot) on Mar 17, 2008 at 16:55 UTC

    The \t in $srcDir is being interpreted as a tab character, so the replacement doesn't match (there's no tab in $path. What you need to do is use quotemeta or \Q to make it match the literal string.

    $path =~ s/\Q$srcDir//i;

    You die if the replacement is a false value, which it will be if it doesn't replace anything. A non-matching replacement isn't an error otherwise.

Thank you
by trout16 (Novice) on Mar 17, 2008 at 17:18 UTC
    Thank you both