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

2
  • your search pattern won't succeed, there is !: at the end of search pattern but not in the string. Commented Jul 13, 2012 at 11:32
  • sorry mistake on my part, !: should have been removed from example Commented Jul 13, 2012 at 11:36

4 Answers 4

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///.

Sign up to request clarification or add additional context in comments.

Comments

0

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

eval "$test =~ s/$search/$replace/";

Comments

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;

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.