On 8/23/05, Jurgens du Toit <[EMAIL PROTECTED]> wrote:
> Hey all...
>
> I want to use groupings, (TEST), and replacement
> variables, $1, $2, etc, in a replacement regex, but
> the replacement is built into a variable. Like so:
>
> #!/usr/bin/perl
>
> my $replace = "urgent \$1";
> my $string = "This is a TEST";
> $string = s/(TEST)/$replace/gi;
> print $string;
>
> It outputs
> This is a urgent $1
>
> Instead of
> This is a urgent TEST
>
> Any ideas?
> Thnx!
> J
>
The are a couple of things going on here. You're immediate problem is
that "urgent \$1" is a double quoted string, and "\" escapes "$"
giving you a literal "$". If you want the variable $1, just use
"urgent $1". If you though \$1 was a reference, what you were really
looking for was: $replace = "urgent " . \$1;
Once you get that sorted out, though, you'll still have an undefined
variable problem, because $1 doesn't yet exist when you declare
$replace. The only way to get around this is to use Peter's double ee
solution, or to do something like the following:
$string =~ s/(TEST)/my $replace = "urgent $1";$replace/gie;
In both cases, though, the result is identical to:
$string =~ s/(TEST)/urgent $1/gi;
If the real goal is to do something other than a straight substition,
consider putting the logic into a subroutine and returning a string
for substitution:
my $string = "This is a TEST";
$string =~ s/(TEST)/&mysub($1)/gie;
print $string;
sub mysub {
my $one = shift;
if ($one =~ /TEST/i) {
return "urgent $one";
} else {
return $one;
}
}
# or something like that
HTH
-- jay
--------------------------------------------------
This email and attachment(s): [ ] blogable; [ x ] ask first; [ ]
private and confidential
daggerquill [at] gmail [dot] com
http://www.tuaw.com http://www.dpguru.com http://www.engatiki.org
values of β will give rise to dom!