Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to work out how Perl substitutions work. We're told that backreference patterns can be used in the substitution by specifying \1, \2 (etc), but it doesn't seem to work.
Snippet below. It tries to turn the string 'Hello sailor' into 'Goodbye sailor', but I get 'Goodbye \1' instead.
(Obviously this isn't sensible way to convert one string to the other, but this is just an example.)
#!/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 Good bye sailor # I got: string is now Good bye \1
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Substitution backreference woes
by Laurent_R (Canon) on Jan 24, 2015 at 15:14 UTC | |
|
Re: Substitution backreference woes
by AnomalousMonk (Archbishop) on Jan 24, 2015 at 21:36 UTC | |
|
Re: Substitution backreference woes
by 2teez (Vicar) on Jan 24, 2015 at 13:21 UTC | |
|
Re: Substitution backreference woes
by Anonymous Monk on Jan 24, 2015 at 12:51 UTC | |
by Anonymous Monk on Jan 24, 2015 at 13:07 UTC | |
by Anonymous Monk on Jan 24, 2015 at 15:30 UTC | |
|
Re: Substitution backreference woes
by LanX (Saint) on Jan 24, 2015 at 13:06 UTC | |
by Anonymous Monk on Jan 24, 2015 at 13:11 UTC | |
by LanX (Saint) on Jan 24, 2015 at 13:17 UTC | |
by LanX (Saint) on Jan 24, 2015 at 13:27 UTC | |
by Anonymous Monk on Jan 24, 2015 at 13:59 UTC |