Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I've got some code which appears to be escaping characters such that they are not treated as metacharacters in a substitution. Below is code which
#!/usr/local/bin/perl use strict; use Data::Dumper; my $s = '<img src="http://www.blah.com?one=[KEY]&two=[KEY]"/>'; my $value = '13.95'; my $q_key = quotemeta('[KEY]'); my $q_value = quotemeta($value); $s =~ s/$q_key/$q_value/g; #$s =~ s/\\././g; print Data::Dumper->Dump([$s], [qw/s/]);
Upon execution, the result is:
$s = '<img src="http://www.blah.com?one=13\\.95&two=13\\.95"/>';
Adding in the substitution commented out above yields correct results:
$s = '<img src="http://www.blah.com?one=13.95&two=13.95"/>';
Is there a way to not escape these characters? It seems that my second substitution is merely a hack. Thanks.

Replies are listed 'Best First'.
Re: variables within substitutions?
by toolic (Bishop) on Jul 05, 2011 at 18:40 UTC
    Since the RHS of the s/// operator is not a regular expression, there is no reason to use quotemeta on it:
    use warnings; use strict; use Data::Dumper; my $s = '<img src="http://www.blah.com?one=[KEY]&two=[KEY]"/>'; my $value = '13.95'; my $q_key = quotemeta('[KEY]'); $s =~ s/$q_key/$value/g; print Data::Dumper->Dump([$s], [qw/s/]); __END__ $s = '<img src="http://www.blah.com?one=13.95&two=13.95"/>';
Re: variables within substitutions?
by jwkrahn (Abbot) on Jul 05, 2011 at 18:50 UTC

    Data::Dumper is adding the extra backslash:

    $ perl -le' use warnings; use strict; use Data::Dumper; my $s = q{<img src="http://www.blah.com?one=[KEY]&two=[KEY]"/>}; print $s; my $value = q{13.95}; print $value; my $q_key = quotemeta( q{[KEY]} ); print $q_key; my $q_value = quotemeta( $value ); print $q_value; $s =~ s/$q_key/$q_value/g; print $s; print Data::Dumper->Dump( [ $s ], [ qw/s/ ] ); ' <img src="http://www.blah.com?one=[KEY]&two=[KEY]"/> 13.95 \[KEY\] 13\.95 <img src="http://www.blah.com?one=13\.95&two=13\.95"/> $s = '<img src="http://www.blah.com?one=13\\.95&two=13\\.95"/>';

    And as others have said, you don't need to quotemeta the string half of the substitution operator.

Re: variables within substitutions?
by jethro (Monsignor) on Jul 05, 2011 at 18:41 UTC

    The substitution string is not parsed as a regular expression, so you don't need to quotemeta it, i.e. don't quotemeta $value