Perl metaprogramming: when is it unsafe to use quotemeta on the REPLACEMENT value of s///?

后端 未结 3 450
小蘑菇
小蘑菇 2021-01-14 16:25

Perl\'s quotemeta operator typically works on the SEARCH side of s///, but in generating code to be compiled with eval, how should I protect the REPLACEMENT tha

3条回答
  •  长发绾君心
    2021-01-14 16:55

    As far as I can tell, perl doesn't do magic things with $replace as long as you don't add the /e flag on the substitute. So quotemeta will always change your result, as it then contains a lot of backslashes.

    #!/usr/bin/perl
    
    $test="test";
    
    $literal_replacement='Hello $1, or \1';
    my $replace = quotemeta $literal_replacement;
    $test =~ s/test/$replace/;
    
    print $test,"\n";
    

    returns:

    Hello\ \$1\,\ or\ \\1
    

    Which is probably not what you want :

提交回复
热议问题