Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regexp interpolating

I have some code:

$a = 'abcdef';
$b = 'f\1d';
$a =~ s/d(e)f/$b/g;
print $a;

I get abcf\1d, but how can I get abcfed?

like image 675
michaeluskov Avatar asked Dec 12 '25 09:12

michaeluskov


2 Answers

$a = 'abcdef';
$b = '"f$1d"';
$a =~ s/d(e)f/$b/gee;
print $a;

Notice that there are two e modifiers in /gee; the second one evaluates "f$1d" string to fed.

As a side note you don't need /g as you're replacing only one pattern occurrence.

like image 116
mpapec Avatar answered Dec 14 '25 01:12

mpapec


$a and $b are special variables, used for sort. So you shoulnd't use them at all.

Better solution is to use another variable and then:

$var_a = 'abcdef';
$var_b = '"f${1}d"';
$var_a =~ s/d(e)f/$var_b/gee;
print $var_a;

The trick is to say, that the substitution uses the \1 first found var ( use the /e flag to avoid using \1 :P )