J
JMI
Hello
Short question, but maybe somebody knows how-to
Let's imagine your program accepts two command line arguments to perform
replaces in a string:
usage: myprogram -s "foo" -r "bar"
where s is the search regex and r the replace regex.
Everything works fine, even grouping with parenthesis, etc. As described in
detail in the cookbook.
But:
When I want to use a captured value in the replacement regex, it does
simply not work. Using all possible syntaxes ( as \$1, or \\$1...) only
leads to either an exmpty value in the replaced string, or a plain-text
"$1" text when too much is escaped.
The code looks like:
my $rx;
if ($case_sensitive) {
$rx = qr/$search_pattern/;
} else {
$rx = qr/$search_pattern/i;
}
print "Patching file:\t$origin\n" if ($debug_mode ||
$verbose_mode);
my $myfile = '';
print "Opening $origin\n" if $debug_mode;
open(OLD, "< $origin")
while (<OLD>) {
$myfile .= $_;
}
print "Closing $origin\n" if $debug_mode;
close(OLD)
open(NEW, "> $playground")
print "Replacing $search_pattern with $replace_pattern\n" if
$debug_mode;
$myfile =~ s/$rx/$replace_pattern/gs;
print NEW $myfile
close(NEW)
Hope it's the right place to find some people having had the same
problem,....
thanks and best regards
JM
Short question, but maybe somebody knows how-to
Let's imagine your program accepts two command line arguments to perform
replaces in a string:
usage: myprogram -s "foo" -r "bar"
where s is the search regex and r the replace regex.
Everything works fine, even grouping with parenthesis, etc. As described in
detail in the cookbook.
But:
When I want to use a captured value in the replacement regex, it does
simply not work. Using all possible syntaxes ( as \$1, or \\$1...) only
leads to either an exmpty value in the replaced string, or a plain-text
"$1" text when too much is escaped.
The code looks like:
my $rx;
if ($case_sensitive) {
$rx = qr/$search_pattern/;
} else {
$rx = qr/$search_pattern/i;
}
print "Patching file:\t$origin\n" if ($debug_mode ||
$verbose_mode);
my $myfile = '';
print "Opening $origin\n" if $debug_mode;
open(OLD, "< $origin")
while (<OLD>) {
$myfile .= $_;
}
print "Closing $origin\n" if $debug_mode;
close(OLD)
open(NEW, "> $playground")
print "Replacing $search_pattern with $replace_pattern\n" if
$debug_mode;
$myfile =~ s/$rx/$replace_pattern/gs;
print NEW $myfile
close(NEW)
Hope it's the right place to find some people having had the same
problem,....
thanks and best regards
JM