in reply to Substitution backreference woes

You are escaping 1 in your code, but what you need is backslash 1, so try \\1 in your variable.

You need to realize that escaping in normal strings is different from "meta characters" in regular expressions.

(yet untested)

update

wasn't the problem here.

Cheers Rolf

PS: Je suis Charlie!

Replies are listed 'Best First'.
Re^2: Substitution backreference woes
by Anonymous Monk on Jan 24, 2015 at 13:11 UTC

    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
      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!

      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.