Perl:我可以在变量中存储反向引用(而不是它们的值)吗?

wuw*_*uwu 6 regex perl

我想做这样的事情:

my $text = "The owls are not what they seem.";  
my $pattern = '(\s+)';  
my $replacement = '-$1-';  
$text =~ s/$pattern/$replacement/g;  
Run Code Online (Sandbox Code Playgroud)

$ text应该是:The-owls- -are- -not- -what- -they--seem.

但当然更像是: - $ 1-owls- $ 1-are- $ 1-not-$ 1-what- $ 1-they-$ 1-seem.

我尝试了各种反向引用($ 1,\ 1,\ g {1},\ g1),但它们都没有用./ e修饰符也不起作用.这有可能吗?

目的是用这样的行改变对象内的一些文本:$ object-> replace('(.)oo','$ 1ar')

还有其他想法如何做到这一点?

非常感谢你.

Sin*_*nür 12

您可以使用/ee以下方式评估然后展开字符串:

my $text = "The owls are not what they seem.";
my $pattern = '(\s+)';
my $replacement = q{"-$1-"};
$text =~ s/$pattern/$replacement/eeg;
Run Code Online (Sandbox Code Playgroud)

来自perldoc perlop:

e 评估右侧作为表达式.

ee 将右侧评估为字符串,然后评估结果

但是,我觉得更安全

my $replacement = sub { "-$1-" };
$text =~ s/$pattern/$replacement->()/eg;
Run Code Online (Sandbox Code Playgroud)

但这一切都取决于你这样做的背景.

  • 我原本想到了潜艇.现在这很明显了.它非常适合.谢谢! (2认同)