Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How defer replacement to access var from search?

Tags:

regex

perl

Basically I want to do this:

#!/usr/bin/perl
$search = qr/(?<X>abc)/;
$_ = "123 abc 456";
s/$search/$+{X} $+{X}/;
print;

something like this:

#!/usr/bin/perl
$search = qr/(?<X>abc)/;
$replace = q($+{X} $+{X});
$_ = "123 abc 456";
s/$search/$replace/;
print;

Result should be 123 abc abc 456.

Is it possible?

$replace needs to be maintained as an external var. So, I don't want the contents just moved to another location. I'm reading this info from a file.

like image 676
Adrian Avatar asked Nov 20 '13 21:11

Adrian


1 Answers

Figured it out. I need to do a double evaluate on the expression (Thanks to @Birei for pointing me at the regex evaluate command. Still can't find it in the perl docs though... had to google. :( )

So it becomes:

#!/usr/bin/perl
$search = qr/(?<X>abc)/;
$replace = q(qq($+{X} $+{X}));
$_ = "123 abc 456";
s/$search/$replace/ee;
print;
like image 59
Adrian Avatar answered Nov 15 '22 04:11

Adrian