5

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.

Adrian
  • 10,246
  • 4
  • 44
  • 110

2 Answers2

4

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;
Adrian
  • 10,246
  • 4
  • 44
  • 110
  • 3
    *"Still can't find it in the perl docs though."* I assume you mean `ee`? See `perldoc perlop` under `s/PATTERN/REPLACEMENT/msixpogce` – ThisSuitIsBlackNot Nov 20 '13 at 22:05
  • 1
    some flags affect actual matching and are in perlre; others are specific to s or m and are documented in perlop. for *why* it works, see http://stackoverflow.com/a/392717/17389 – ysth Nov 20 '13 at 22:11
3

Try with a function an add a flag to evaluate the replacement part, like this:

#!/usr/bin/env perl

$search = qr/(?<X>abc)/;
$replace = sub { qq($+{X} $+{X}) };
$_ = "123 abc 456";
s/$search/$replace->()/e;
print;

It yields:

123 abc abc 456
Birei
  • 35,723
  • 2
  • 77
  • 82
  • Also, I can't have the contents just moved to another location. I need to move the contents there. – Adrian Nov 20 '13 at 21:41