I
Ian
Hi,
Hopefully a simple question but my brain is hurting...
I want to make a regex substitution, using search and replace
patterns contained in variables. What I want to do is:
$f = "fred.abc";
$f =~ s/(.*)\.abc/$1.def/;
print "$f\n";
but where the two parts of the substitution are variables:
my $to_pattern = "(.*)\\.abc";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n";
Unfortunately this doesn't seem to work, where the first example
correctly prints out "fred.def" the second one doesn't seem to
do the back-substitution, and just prints "$1.def".
Is this possible, and if so, what quoting magic do I need to make
it work???
TIA,
Ian.
#!/usr/bin/perl -w
use strict;
my $f;
$f = "fred.abc";
$f =~ s/(.*)\.abc/$1.def/;
print "$f\n"; # prints "fred.def" (correct)
$f = "joe.abc";
my $to_pattern = "(.*)\\.abc";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n"; # prints "$1.def"
# end
Hopefully a simple question but my brain is hurting...
I want to make a regex substitution, using search and replace
patterns contained in variables. What I want to do is:
$f = "fred.abc";
$f =~ s/(.*)\.abc/$1.def/;
print "$f\n";
but where the two parts of the substitution are variables:
my $to_pattern = "(.*)\\.abc";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n";
Unfortunately this doesn't seem to work, where the first example
correctly prints out "fred.def" the second one doesn't seem to
do the back-substitution, and just prints "$1.def".
Is this possible, and if so, what quoting magic do I need to make
it work???
TIA,
Ian.
#!/usr/bin/perl -w
use strict;
my $f;
$f = "fred.abc";
$f =~ s/(.*)\.abc/$1.def/;
print "$f\n"; # prints "fred.def" (correct)
$f = "joe.abc";
my $to_pattern = "(.*)\\.abc";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n"; # prints "$1.def"
# end