Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

s/$foo/$bar/ when $foo has metacharacters in it

by bcrowell2 (Friar)
on Dec 20, 2007 at 22:26 UTC ( #658303=perlquestion: print w/ replies, xml ) Need Help??
bcrowell2 has asked for the wisdom of the Perl Monks concerning the following question:

I often want to do something like $a =~ s/$b/$c/g , where $b is a variable that may have regex metacharacters in it. Here's an example of the problem:
my $a = "$"; my $b = "$"; my $c = "x"; $a =~ s/$b/$c/g; print "a=$a\n";
This results in an error, because the string $b has a regex metacharacter, $, in it. Here's the alternative I've come up with so far:
# conceptually, the following is like $a=~s/$b/$c/, but is safe if $b +has metacharacters in it sub string_substitution_one { my $a_ref = shift; my $b = shift; my $c = shift; my $a = $$a_ref; my $debug = ($b eq '$m$'); my $i=index($a,$b); return 0 if $i == -1; my $z = ''; if ($i>0) {$z = $z . substr($a,0,$i)} $z = $z . $c; if ($i+length($b)<length($a)) {$z = $z . substr($a,$i+length($b),len +gth($a)-($i+length($b)))} $$a_ref = $z; return 1; } # conceptually, the following is like $a=~s/$b/$c/g, but is safe if $b + has metacharacters in it sub string_substitution_global { my $a_ref = shift; my $b = shift; my $c = shift; my $found = 0; while (string_substitution_one($a_ref,$b,$c)) { $found = 1; } return $found; }
Is there a simpler way to do this? I'm thinking of making this into a module, because I have several different programs that use it, but it seems like there must be an easier way to do such a common task. TIA!

Comment on s/$foo/$bar/ when $foo has metacharacters in it
Select or Download Code
Re: s/$foo/$bar/ when $foo has metacharacters in it
by FunkyMonk (Canon) on Dec 20, 2007 at 22:30 UTC
    You can use quotemeta, either as a function, or as \Q...\E (update: Relashed my slashes, thanks ikegami):
    $b = quotemeta $b; $a =~ s/$b/$c/g; #or $a =~ s/\Q$b/$c/g; # \E not needed at end of pattern

      Excellent -- thanks!
Re: s/$foo/$bar/ when $foo has metacharacters in it
by sh1tn (Priest) on Dec 20, 2007 at 22:44 UTC
    In addition: perldoc -q quote and quote.


Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://658303]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2014-10-22 02:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (112 votes), past polls