in reply to Appending backslash to a string

If you want to include a variable inside a regex, but don't want the data in the variable treated as part of the regex then you wrap it in \Q \E (which i beleve stand for quote and end, its at least how i rememebr)

#!/usr/bin/perl use strict; use warnings; my $char = '\\'; my $str = 'bla'; $str =~ s/\Q$char\E?$/$char/; print "$str\n";

___________
Eric Hodges

Replies are listed 'Best First'.
Re^2: Appending backslash to a string
by wind (Priest) on Aug 11, 2007 at 00:31 UTC
Re^2: Appending backslash to a string
by garu (Scribe) on Aug 11, 2007 at 00:56 UTC
    Damn, I knew that! And to think I used it a couple pages up the original code... guess I was tired.

    Anyway, thanks for the quick response! :-)

Re^2: Appending backslash to a string
by ThomMerton2242 (Initiate) on Jun 29, 2020 at 13:37 UTC

    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!

      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.

      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.