For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > August 2005 > Variables in replace regex









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Variables in replace regex
Jurgens du Toit

2005-08-23, 6:56 pm

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



________________________________________
___________________
To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com
Peter Scott

2005-08-23, 6:56 pm

On Tue, 23 Aug 2005 14:02:03 +0100, Jurgens du Toit wrote:
> 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


The right usage of the /e (evaluate) modifier will do this (which is
depressingly nonobvious):

$string = s/(TEST)/qq("$replace")/giee;

The first /e turns the replacement into qq(urgent TEST), the second
one evaluates that expression and interpolates it.

--
Peter Scott
http://www.perlmedic.com/
http://www.perldebugged.com/

Chris

2005-08-23, 6:56 pm

Jurgens du Toit 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:


Why do you want to build it into the variable? can't you just add it
your replacement as below?

> #!/usr/bin/perl
>
> my $replace = "urgent \$1";
> my $string = "This is a TEST";
> $string = s/(TEST)/$replace/gi;


For a start you've missed off the ~ in your substitution!

> print $string;
>
> It outputs
> This is a urgent $1
>
> Instead of
> This is a urgent TEST
>
> Any ideas?
> Thnx!
> J
>


How about this?:

#!/usr/bin/perl

use strict;
use warnings;

my $replace = "urgent";
my $string = "This is a TEST";
$string =~ s/(TEST)/$replace $1/gi;
print $string;
Peter Scott

2005-08-23, 6:56 pm

On Tue, 23 Aug 2005 06:30:07 -0700, I wrote:
>
> $string = s/(TEST)/qq("$replace")/giee;


I mean =~ of course. Wups.

--
Peter Scott
http://www.perlmedic.com/
http://www.perldebugged.com/

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com