s/$pattern_to_match/$pattern_to_replace/ -- how can i use matched expressions?

M

Mithras

Hi all,

I want to use the substitution operator with variables rather than
string literals -- no problem, right?

My problem comes when I try to use the $1, $2, etc. variables to refer
to the matched expressions.
For example:

$pattern_to_match = 'I am (.*)';
$pattern_to_replace = 'You are $1';
$line =~ s/$pattern_to_match/$pattern_to_replace/g;

For example, if $line contains 'I am green', I want it to be replace
with 'You are green'.
However, the code fragment above would result in 'You are ' -- the $1
variable doesn't work as the match substitution...

Can anyone help me out?
I realize I may be able to work something out with the s///e option,
but this looks a little too complex for what I want to do.

TIA
 
J

Jay Tilton

(e-mail address removed) (Mithras) wrote:

: I want to use the substitution operator with variables rather than
: string literals -- no problem, right?
:
: My problem comes when I try to use the $1, $2, etc. variables to refer
: to the matched expressions.
: For example:
:
: $pattern_to_match = 'I am (.*)';
: $pattern_to_replace = 'You are $1';

Don't let yourself call the replacement string a "pattern."
Badly named variables will only bring confusion.

: $line =~ s/$pattern_to_match/$pattern_to_replace/g;
:
: For example, if $line contains 'I am green', I want it to be replace
: with 'You are green'.
: However, the code fragment above would result in 'You are ' -- the $1
: variable doesn't work as the match substitution...
:
: Can anyone help me out?
: I realize I may be able to work something out with the s///e option,
: but this looks a little too complex for what I want to do.

Not all that complex.

my $pattern_to_match = 'I am (.*)';
my $string_to_replace = '"You are $1"';
my $line = 'I am green';
$line =~ s/$pattern_to_match/$string_to_replace/eeg;
print $line;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top