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

Hi,
How can I do a substitution to change "c:\tmp/sup" to "c:\\tmp\\sup". I tried s/\/|\\/\\\\/ but it did not work.

--thanks

Edit by tye, title, formatting

Replies are listed 'Best First'.
Re: substitution
by Thelonius (Priest) on May 19, 2003 at 18:31 UTC
    The only thing wrong with yours is that it needs a /g on the end of the substitution. But it might be more readable to write:
    s![/\\]!\\\\!g;
Re: substitution
by Popcorn Dave (Abbot) on May 19, 2003 at 18:31 UTC
    Try this instead:
    use strict; my $t = 'c:\tmp/sup'; print "$t\n"; $t =~ s?\\|/?\\\\?g; print "Modified\n$t\n";

    You need the \\ to match a single \ and a \\\\ to change it to a \\.

    Also by using a character other than the / for your delimeter you don't have to escape it in the regex. I find that's a bit cleaner to read without all the escaping.

    Hope that helps!

    There is no emoticon for what I'm feeling now.

Re: substitute \ and / with \\ ?
by BrowserUk (Patriarch) on May 19, 2003 at 18:48 UTC

    Might be worth mentioning that for pretty much anything that you do with paths internal to perl, you can use "c:/tmp/sup/$filename" which is a lot easier on the eyes than "c:\\tmp\\sup\\$filename".

    You can also get away with coding 'c:\tmp\sup' . $filename where you need constants that are going to be passed to CMD.EXE or other uncooperative .exe's, so long as you use single quotes.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
Re: substitution
by sauoq (Abbot) on May 19, 2003 at 18:35 UTC

    That'll work but you need a /g modifier. Also, you might try using a different delimiter to make it easier to read. Try s!\\|/!\\\\!g instead.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: substitute \ and / with \\ ?
by Mr. Muskrat (Canon) on May 19, 2003 at 18:32 UTC

    This works for me:

    my $string = 'c:\\tmp/sup'; $string =~ s![\\/]!\\\\!g; print $string,$/; __DATA__ c:\\tmp\\sup

    Once again, I am too late...

Re: substitute \ and / with \\ ? (transliteration, not substitution)
by grinder (Bishop) on May 19, 2003 at 19:25 UTC

    What you want to do doesn't require regular expressions at all. You can do it with a transliteration, using the tr operator

    my $path = 'c:\\tmp/sup'; $path =~ tr{/}{\\};

    Oops. Sorry, misread the question. Which just goes to show that backslashes are truly the work of the devil.

    _____________________________________________
    Come to YAPC::Europe 2003 in Paris, 23-25 July 2003.