6

I have a Perl script that reads regex search and replace values from an INI file.

This works fine until I try to use capture variables ($1 or \1). These get replaced literally with $1 or \1.

Any ideas how I can get this capture functionality to work passing regex bits via variables? Example code (not using an ini file)...

$test = "word1 word2 servername summary message";

$search = q((\S+)\s+(summary message));
$replace = q(GENERIC $4);

$test =~ s/$search/$replace/;
print $test;

This results in ...

word1 word2 GENERIC $4

NOT

word1 word2 GENERIC summary message

thanks

andyml73
  • 77
  • 1
  • 5

4 Answers4

6

Use double evaluation:

$search = q((\S+)\s+(summary message));
$replace = '"GENERIC $1"';

$test =~ s/$search/$replace/ee;

Note double quotes in $replace and ee at the end of s///.

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
0

try subjecting the regex-sub to eval, be warned that the replacement is coming from external file

eval "$test =~ s/$search/$replace/";
tuxuday
  • 2,977
  • 17
  • 18
0

Another interesting solution would use look-aheads (?=PATTERN)

Your example would then only replace what needs to be replaced:

$test = "word1 word2 servername summary message";

# repl. only ↓THIS↓
$search = qr/\S+\s+(?=summary message)/;
$replace = q(GENERIC );

$test =~ s/$search/$replace/;
print $test;
amon
  • 57,091
  • 2
  • 89
  • 149
0

If you like amon's solution, I assume that the "GENERIC $1" is not configuration (especially the '$1' part in it). In that case, I think there's an even more simple solution without the use of look-aheads:

$test = "word1 word2 servername summary message";
$search = qr/\S+\s+(summary message)/;
$replace = 'GENERIC';
$test =~ s/$search/$replace $1/;

Although there's nothing really bad about (?=PATTERN) of course.

CowboyTim
  • 57
  • 4