Regex:: using variables to hold replacement text
From: William Lewis Brown (bbrown_at_addtoit.com)
Date: 09/30/04
- Next message: Ged Murphy: "RE: printing block of text"
- Previous message: Gabor Urban: "RE: printing block of text"
- Next in thread: Gunnar Hjalmarsson: "Re: Regex:: using variables to hold replacement text"
- Reply: Gunnar Hjalmarsson: "Re: Regex:: using variables to hold replacement text"
- Maybe reply: Bob Showalter: "RE: Regex:: using variables to hold replacement text"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
To: beginners@perl.org Date: Thu, 30 Sep 2004 09:48:08 -0400
Hi,
I have a need to store replacement text for a regex substitution
in a variable. In other words, I have code in a perl script like so::
$foo =~ s/(.*)bar(.*)/$replacement/g;
The $replacement string needs to contain a "reference" to $1. In other
words, the string $replacement will contain the string "$1". I need to
have the $1 string interpreted so that it will be replaced with the text
of the first '(.*)' expression. I have not yet found a way to get this
to happen. The "$1" string always seems to be interpreted as a plain
string.
Can someone tell me how to write the substitution correctly? I
have included an example below.
Thanks for your help and your time.
Bill Brown
bbrown@addtoit.com
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> $ perl -d
>
> Loading DB routines from perl5db.pl version 1.0402
> Emacs support available.
>
> Enter h or `h h' for help.
>
> my $foo="yada bar yada";
> my $replacement='$1';
> $foo =~ s/(.*)bar(.*)/$replacement/g;
> print $foo;
> my $foo="yada bar yada";
> $foo =~ s/(.*)bar(.*)/$1/g;
> print $foo
> main::(-:1): my $foo="yada bar yada";
> DB<1> n
> main::(-:2): my $replacement='$1';
> DB<1> n
> main::(-:3): $foo =~ s/(.*)bar(.*)/$replacement/g;
> DB<1> n
> main::(-:4): print $foo;
> DB<2> n
> $1 [ BAD OUTPUT ]
> main::(-:5): my $foo="yada bar yada";
> DB<2> n
> main::(-:6): $foo =~ s/(.*)bar(.*)/$1/g;
> DB<2> n
> main::(-:7): print $foo
> DB<2> n
> yada [ GOOD OUTPUT]
> Debugged program terminated. Use q to quit or R to restart,
> use O inhibit_exit to avoid stopping after program termination,
> h q, h R or h O to get additional info.
> DB<2>
-- William L. Brown Email: bbrown@addtoit.com
- Next message: Ged Murphy: "RE: printing block of text"
- Previous message: Gabor Urban: "RE: printing block of text"
- Next in thread: Gunnar Hjalmarsson: "Re: Regex:: using variables to hold replacement text"
- Reply: Gunnar Hjalmarsson: "Re: Regex:: using variables to hold replacement text"
- Maybe reply: Bob Showalter: "RE: Regex:: using variables to hold replacement text"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|