in reply to Re: Appending backslash to a string
in thread Appending backslash to a string

I have searched high and low for a solution to a similar problem I am grappling with. I am writing a complex Perl script, part of which attempts to escape all url forward slashes by preceding them with backslashes via regex. I am able to replace forward slashes with backslashes, using variations of the following:

$test =~ tr [\\] [\/];
But I want my output to look like the following:
http:\/\/www.myurl.com\/me.html

Any advice would be extremely helpful. Thanks!

Replies are listed 'Best First'.
Re^3: Appending backslash to a string
by haukex (Archbishop) on Jun 29, 2020 at 14:49 UTC

    Please note that you're replying to a 13-year old thread, you'll probably get better exposure by posting a new question in SoPW, following the advice in How do I post a question effectively? Anyway, tr/// only replaces single characters, you may want s///g instead (or in this case, s{}{}g to avoid Leaning Toothpick Syndrome). However, in my experience, an escape usually doesn't come alone (do you need to escape backslashes too?), so it would be much better if you told us why you need to escape slashes, perhaps there's a much better method than regexes that we would miss otherwise.

Re^3: Appending backslash to a string
by hippo (Archbishop) on Jun 29, 2020 at 15:46 UTC

    Here is a simple SSCCE showing how to achieve what you have asked for.

    use strict; use warnings; use Test::More tests => 1; my $have = 'http://www.myurl.com/me.html'; my $want = 'http:\/\/www.myurl.com\/me.html'; $have =~ s#/#\\/#g; is $have, $want;

    Note however that I agree with haukex that under most circumstances the result which you say you want is maybe not so useful and that this does sound rather like an XY Problem.