Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: passing regex search and replace using variables

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

like image 650
andyml73 Avatar asked Jul 13 '12 11:07

andyml73


People also ask

How do I search and replace in Perl?

Performing a regex search-and-replace is just as easy: $string =~ s/regex/replacement/g; I added a “g” after the last forward slash. The “g” stands for “global”, which tells Perl to replace all matches, and not just the first one.

How do I replace a variable in Perl?

print $url if $url =~ s/$search/$replace/ee; This will give us: Port and host name lower case.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

What is $_ in Perl script?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }


1 Answers

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

like image 85
Igor Chubin Avatar answered Oct 23 '22 04:10

Igor Chubin