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

I am trying to replace a forward slash / with a backslash \
I have tried
$Doc =~ s/\//\\/;
and it doesn't seem to work.

Replies are listed 'Best First'.
Re: Regular Expressions Problem
by eye (Chaplain) on Dec 09, 2008 at 21:11 UTC
    Another approach to this is to use the "tr" command:
    $Doc =~ tr/\//\\/;
    The "tr" command is usually more efficient for character substitutions. You can also use a delimiter other than slash (/) as GrandFather suggested. In this instance, I prefer using paired delimiters like:
    $Doc =~ tr{/}{\\};
Re: Regular Expressions Problem
by GrandFather (Saint) on Dec 09, 2008 at 20:55 UTC

    That will replace a / with a \, but only one. Quite likely you need to replace many. The /g switch does that, but there is another trick it is worth knowing (many actually, but we'll focus on just this one). Consider:

    my $doc = 'This /and/ that.'; $doc =~ s!/!\\!g; print $doc;

    Prints:

    This \and\ that.

    Note the use of ! to delimit the regex parts to avoid the picket fence effect you get using the default / and needing to quote stuff with \.

    For more regex goodness see perlretut and perlre.


    Perl's payment curve coincides with its learning curve.