First Namea A
First Namea A

Reputation: 21

in Perl, how do i write regex matched string

I want to write $1 on other line for replacement;

my $converting_rules = +{
    '(.+?)' => '$1',
};

my $pre     = $converting_rule_key;
my $post    = $converting_rules->{$converting_rule_key};
#$path_file =~ s/$pre/$post/; // Bad... 
$path_file =~ s/$pre/$1/; // Good!

On Bad, $1 is recognized as a string '$1'. But I wqnt to treat it matched string. I have no idea what to do...plz help me!

Upvotes: 0

Views: 90

Answers (2)

ikegami
ikegami

Reputation: 385590

$x = '$1.00';
print qq/$x/;

prints $1.00, so it's no surprise that

$x = '$1.00';
s/(abc)/$x/;

substitutes with $1.00.

What you have there is a template, yet you did nothing to process this template. String::Interpolate can handle such templates.

use String::Interpolate qw( interpolate );
$rep = '$1';
s/$pat/ interpolate($rep) /e;

Upvotes: 0

aschepler
aschepler

Reputation: 72271

The trouble is that s/$pre/$post/ interpolates the variables $pre and $post, but will not recursively interpolate anything in them that happens to look like a variable. So you want to add an extra eval to the replacement, with the /ee flag:

$path_file =~ s/$pre/$post/ee;

Upvotes: 2

Related Questions