Perl metaprogramming: when is it unsafe to use quotemeta for REPLACEMENT s ///?

The perl quotemetaoperator usually works on the search side s///, but in generating code that needs to be compiled with eval, how should I protect REPLACEMENT, which should be used literally, but can contain bits like $1?

With form code

my $replace = quotemeta $literal_replacement;

my $code = eval <<EOCode;
  sub { s/.../$replace/ }
EOCode

when will this lead to syntax errors or unexpected results?

+3
source share
3 answers

, perl $, /e . , quotemeta , .

#!/usr/bin/perl

$test="test";

$literal_replacement='Hello $1, or \1';
my $replace = quotemeta $literal_replacement;
$test =~ s/test/$replace/;

print $test,"\n";

:

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

, , :

+7

( /e, eval, /e). Perl 5 , , . , :

my $foo = 5;
my $bar = '$foo';
my $baz = "$foo $bar"; 
print "$baz\n"; #this is 5 $foo not 5 5
+1

, , :

$test =~ s<test>'$replace';
+1
source

Source: https://habr.com/ru/post/1764366/


All Articles