kay*_*oll 169 regex perl replace
在Perl中,使用正则表达式对字符串执行替换并将值存储在另一个变量中而不更改原始值的好方法是什么?
我通常只是将字符串复制到一个新变量,然后将其绑定到正在s///替换新字符串的正则表达式,但我想知道是否有更好的方法来做到这一点?
$newstring = $oldstring;
$newstring =~ s/foo/bar/g;
Run Code Online (Sandbox Code Playgroud)
Joh*_*usa 242
这是我用来获取字符串的修改副本而不更改原始字体的习语:
(my $newstring = $oldstring) =~ s/foo/bar/g;
Run Code Online (Sandbox Code Playgroud)
在perl 5.14.0或更高版本中,您可以使用新的/r 非破坏性替换修饰符:
my $newstring = $oldstring =~ s/foo/bar/gr;
Run Code Online (Sandbox Code Playgroud)
注意:上述解决方案也没有g.它们也适用于任何其他修饰符.
Pat*_*Pat 42
该声明:
(my $newstring = $oldstring) =~ s/foo/bar/g;
Run Code Online (Sandbox Code Playgroud)
这相当于:
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;
Run Code Online (Sandbox Code Playgroud)
或者,从Perl 5.13.2开始,您可以使用/r非破坏性替换:
use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;
Run Code Online (Sandbox Code Playgroud)
Sam*_*ton 21
在use strict,说:
(my $new = $original) =~ s/foo/bar/;
Run Code Online (Sandbox Code Playgroud)
代替.
小智 9
单线解决方案作为一个shibboleth比良好的代码更有用; 好的Perl程序员会知道它并理解它,但它比你刚开始的两行复制和修改联接更不透明和可读.
换句话说,这样做的好方法就是你已经这样做了.以可读性为代价的不必要的简洁并不是一个胜利.