gpt4 book ai didi

regex - Perl 元编程 : when is it unsafe to use quotemeta on the REPLACEMENT value of s///?

转载 作者:行者123 更新时间:2023-12-01 09:08:51 27 4
gpt4 key购买 nike

Perl 的 quotemeta运算符通常在 s/// 的 SEARCH 端工作,但在生成要使用 eval 编译的代码时,我应该如何保护应该按字面意思使用但可能包含诸如 $1 之类的位的 REPLACEMENT?

用表单的代码

my $replace = quotemeta $literal_replacement;

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

什么时候会产生语法错误或令人惊讶的结果?

最佳答案

据我所知,只要您不在替代品上添加/e 标志,perl 就不会使用 $replace 做神奇的事情。所以 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

这可能不是你想要的:

关于regex - Perl 元编程 : when is it unsafe to use quotemeta on the REPLACEMENT value of s///?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3694851/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com