如何在替换中使用变量作为修饰符
有没有办法在替换中使用变量作为修饰符?
my $search = 'looking';
my $replace = '"find: $1 ="';
my $modifier = 'ee';
s/$search/$replace/$modifier;
我需要使用哈希数组来使用不同的修饰符进行批量搜索替换。
Is there a way to use a variable as modifier in a substitution?
my $search = 'looking';
my $replace = '"find: $1 ="';
my $modifier = 'ee';
s/$search/$replace/$modifier;
I need to use an array of hashes to make bulk search-replace with different modifiers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然使用
eval
编译新替换的方法可能是最简单的,但您可以创建更加模块化的替换:这只是进行了轻微测试,并留给读者作为练习实现其他标志,例如
g
While the method using
eval
to compile a new substitution is probably the most straightforward, you can create a substitution that is more modular:This is only lightly tested, and it is left as an exercise for the reader to implement other flags like
g
如果您戴上护目镜和除零服,则可以使用
eval
。例如:
You could use
eval
, if you put on your safety goggles and your divide-by-zero suit.E.g.:
嗯,如果我必须这样做,我会这样做:
您可能想要使用的不同修饰符只有这么多,所以我认为这很简单。
您可以使用
eval
来实现此目的,但它非常混乱。Hm, if I had to do it I would do like this:
There are only so many different modifiers you might want to use so I think this is easy enough.
You can use
eval
for this, but it's awfully messy.当然
s/$search/$replace/
按您的预期工作。动态修饰符并不简单。对于
pimsx
的常规匹配修饰符,您可以使用Perl的扩展模式作为模式的一部分动态修改修饰符标志。它们的形式为(?pimsx-imsx)
用于打开/关闭这些修饰符。对于
s//
e
和ee
形式,您可以使用(?{ perl code})
中记录的相同的 perlre 部分。对于所有eval
e
或ee
形式,请考虑结果代码的安全性!据我所知,没有任何形式可以将全局修改为第一个匹配,因此全局与第一个匹配需要是单独的语句。
Of course
s/$search/$replace/
work as you expect. It is the dynamic modifiers that are not straightforward.For the regular match modifiers of
pimsx
you can use Perl's Extended Patterns to modify the modifier flags on the fly as part of your pattern. These are of the form(?pimsx-imsx)
to turn on / off those modifiers.For the
s//
e
andee
forms, you can use(?{ perl code})
documented in the same perlre section. For all ofeval
e
oree
forms, consider the security of the resulting code!There is no form to modify global to first match that I am aware of, so global vs first match would need to be separate statements.
这是 Kinopiko 的回答和评估的组合。
这里使用
eval
以受控且可维护的方式生成查找表,查找表用于保存所有看起来不太好玩的if..elsif..elsif。(经过非常简单的测试)
要完全有用,这需要:
Here's a combination of Kinopiko's answer and eval.
eval
is used here to generate the lookup table in a controlled and maintainable fashion, and a lookup table is used to save all the if.. elsif.. elsif which are not too fun to look at.(very lightly tested)
To be fully useful this needs: