Solution 1: String::Substitution
Use the String::Substitution package :
use String::Substitution qw(gsub_modify); my $find = 'some_(\w+)_thing'; my $repl = 'no_$1_stuff'; my $text = "some_strange_thing"; gsub_modify($text, $find, $repl); print $text,"\n";
The replacement string only interpolates (the term is used loosely) numbered matching variables (for example, $1 or ${12} ). See "interpolate_match_vars" for more information.
This module does not save or interpolate $& to avoid "significant performance degradation " (see Perlvar ).
Solution 2: Data::Munge
This is the solution mentioned by Grinnz in the comments below.
Data::Munge can be used as follows:
use Data::Munge; my $find = qr/some_(\w+)_thing/; my $repl = 'no_$1_stuff'; my $text = 'some_strange_thing'; my $flags = 'g'; print replace($text, $find, $repl, $flags);
Quick and dirty way (if the replacement does not contain double quotes and security is not considered)
DISCLAIMER : I provide this solution, as this approach can be found on the Internet, but its warnings are not explained. Do not use it in production .
With this approach, you cannot have a replacement string that contains " double quotes”, and since this is equivalent to passing anyone who writes direct access to the configuration file to the configuration file, it should not be open to web users (as mentioned by Daniel ) Martin ).
You can use the following code:
#!/usr/bin/perl my $match = qr"some_(\w+)_thing"; my $repl = '"no_$1_stuff"'; my $text = "some_strange_thing"; $text =~ s/$match/$repl/ee; print "Result: $text\n";
Watch the IDEONE Demo
Result:
Result: no_strange_stuff
you should
- Declare a replacement in
'"..."' so you can evaluate $1 later - Use
/ee to force a double evaluation of the variables in the replacement.
The modifier, available specifically for search and replace, is the s///e rating modifier. s///e treats the replacement text as Perl code, not as a double-quoted string. The value that the code returns is replaced with the corresponding substring. s///e is useful if you need to calculate a little while replacing text.
You can use qr to instantiate a pattern for a regular expression ( qr"some_(\w+)_thing" ).