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
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.
print $url if $url =~ s/$search/$replace/ee; This will give us: Port and host name lower case.
$@ 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.
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"; }
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///
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With