如何在替换中使用变量作为修饰符

bem*_*m33 5 regex variables perl modifier substitution

有没有办法在替换中使用变量作为修饰符?

my $search = 'looking';
my $replace = '"find: $1 ="';
my $modifier = 'ee';

s/$search/$replace/$modifier;
Run Code Online (Sandbox Code Playgroud)

我需要使用哈希数组来使用不同的修饰符进行批量搜索替换.

小智 3

嗯,如果我必须这样做,我会这样做:

use warnings;
use strict;
my @stuff = (
{
    search => "this",
    replace => "that",
    modifier => "g",
},
{
    search => "ono",
    replace => "wendy",
    modifier => "i",
}
);
$_ = "this ono boo this\n";
for my $h (@stuff) {
    if ($h->{modifier} eq 'g') {
        s/$h->{search}/$h->{replace}/g;
    } elsif ($h->{modifier} eq 'i') {
        s/$h->{search}/$h->{replace}/i;
    }
    # etc.
}
print;
Run Code Online (Sandbox Code Playgroud)

您可能想要使用的不同修饰符只有这么多,所以我认为这很简单。

你可以用eval这个,但它非常混乱。

  • 情人眼里出西施。我发现这比评估解决方案更混乱。 (7认同)
  • @runrig:在这种情况下,“混乱”并不是指代码的样子。如果您使用“eval”,则需要处理许多难以跟踪的错误。 (2认同)