perl 中的内联正则表达式替换 [英] Inline regex replacement in perl
问题描述
有没有办法用正则表达式内联替换文本,而不是从变量中取出文本并将其存储在变量中?
Is there a way to replace text with a regex inline, rather than taking the text from a variable and storing it in a variable?
我是 perl 初学者.我经常发现自己在写作
I'm a perl beginner. I often find myself writing
my $foo = $bar;
$foo =~ s/regex/replacement/;
doStuff($foo)
我最想写的地方
doStuff($bar->replace(s/regex/replacement/));
之类的,而不是使用临时变量和三行.
or the like, rather than using a temporary variable and three lines.
有没有办法做到这一点?显然,当正则表达式足够复杂时,将其拆分以便更好地解释是有意义的,但是当它只是 s/\s//g
时,将代码与其他变量混在一起感觉是错误的.
Is there a way to do this? Obviously when the regex is sufficiently complicated it makes sense to split it out so it can be better explained, but when it's just s/\s//g
it feels wrong to clutter the code with additional variables.
推荐答案
从 perl 5.14 开始你可以使用 非破坏性替换 以实现所需的行为.
Starting from perl 5.14 you can use Non-destructive substitution to achieve desired behavior.
使用 /r
修饰符来这样做:
Use /r
modifier to do so:
doStuff($bar=~s/regex/replacement/r);
这篇关于perl 中的内联正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!