in reply to Re: Substitution backreference woes
in thread Substitution backreference woes

That seems to produce the same result, namely:

string is now Goodbye \1

#!/usr/bin/perl use strict; use diagnostics; use warnings; my $string = 'Hello sailor'; my $regex = 'Hello (.*)'; my $substitution = 'Goodbye \\1'; $string =~ s/$regex/$substitution/; print "string is now $string \n"; # I wanted: string is now Goodbye sailor # I got: string is now Goodbye \1

Replies are listed 'Best First'.
Re^3: Substitution backreference woes
by LanX (Saint) on Jan 24, 2015 at 13:17 UTC
    yeah sorry I wasn't able to test from Android, the problem is that the substitution part of s/// is supposed to be a literal. Otherwise you have to apply the /e eval modifiers.

    my $string = 'Hello sailor'; my $regex = 'Hello (.*)'; # my $substitution = 'Goodbye \1'; $string =~ s/$regex/Goodbye $1/; print "string is now <$string> \n";

    /usr/bin/perl -w /tmp/regex.pl string is now <Goodbye sailor>

    Please note that \1 is somehow deprecated in the substitution part and will cause warnings.

    Its only legitimate use is in the match part for backreference.

    Cheers Rolf

    PS: Je suis Charlie!

Re^3: Substitution backreference woes
by LanX (Saint) on Jan 24, 2015 at 13:27 UTC
    That's how you go if you want to hold the substitution part in a variable.

    my $string = 'Hello sailor'; my $regex = 'Hello (.*)'; my $substitution = '"Goodbye $1"'; $string =~ s/$regex/$substitution/ee; print "string is now <$string> \n";

    /usr/bin/perl -w /tmp/regex.pl string is now <Goodbye sailor>

    Cheers Rolf

    PS: Je suis Charlie!

      Yes, that seems to work perfectly. Thank you.