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

Hello wise ones, I'm having a problem (or am just confused) with interpolation using the substitution operator. This is my code:
$ScriptPath = "\\\\SERVER\\C\$\\APP\\BIN"; $file = "$ScriptPath\\somefile.txt"; $file =~ s/$ScriptPath\\//;
Shouldn't $file now be "somefile.txt" ? Thanks!

Replies are listed 'Best First'.
Re: s/// and variable interpolation (use a module instead)
by grinder (Bishop) on Dec 16, 2002 at 13:26 UTC

    Rather than battling with regular expressions, I would choose to use a module to deal with this problem:

    use File::Basename qw/basename/; my $file = shift || '//server/c$/app/bin/somefile.txt'; print( basename($file), "\n" );

    The beauty of this approach is twofold. Firstly, the module File::Basename is supplied as part of the core Perl distribution, so it is always present (unless you happen to stumble across a particularly stripped-down Perl installation).

    Secondly, it is written to be platform-independent. Take that code anywhere, and it will perform as expected. One less damned thing to go wrong.


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
Re: s/// and variable interpolation
by mce (Curate) on Dec 16, 2002 at 13:27 UTC
    Hi, welkome to the world of metacharacters:-)
    use this code to debug this problem.
    use re debug; $ScriptPath = "\\\\SERVER\\C\$\\APP\\BIN"; $file = $ScriptPath."\\somefile.txt"; warn $file; warn $ScriptPath; $file =~ s|\Q$ScriptPath\E||; warn $file;
    The re debug is very usefull for these kind of problems.

    I hope this helps.


    ---------------------------
    Dr. Mark Ceulemans
    Senior Consultant
    IT Masters, Belgium

Re: s/// and variable interpolation
by LTjake (Prior) on Dec 16, 2002 at 13:27 UTC
    To make things a little more readable, I'd use q() to your advantage:
    $ScriptPath = q(\\SERVER\C\$\APP\BIN); $file = "$ScriptPath\\somefile.txt"; $file =~ s/\Q$ScriptPath\E\\//; print $file;
    prints somefile.txt. Also, note the use of \Q...\E to escape meta characters from the interpolated string.

    HTH

    --
    "I don't intend for this to take on a political tone. I'm just here for the drugs." --Nancy Reagan
Re: s/// and variable interpolation
by CubicSpline (Friar) on Dec 16, 2002 at 13:19 UTC
    I believe that what's happening is that when you use $ScriptPath in your regex, the backslashes are read as escaping the next character ... so essentially your regex is looking for the string "\SERVERCAPPBIN". Try changing the last line from
    $file =~ s/$ScriptPath\\//;
    to:
    $file =~ s/\Q$ScriptPath\E\\//;
    to tell the regex to treat those as literal backslashes and not as metacharacters.

    ~CubicSpline
    "No one tosses a Dwarf!"