这个问题在这里已经有了答案:
How do I perform a Perl substitution on a string while keeping the original?
(8 个回答)
2年前关闭。
在 Perl 中,运算符 s/
用于替换字符串的一部分。现在s/
将更改其参数(字符串)。但是,我想在打印之前替换字符串的一部分,如
print "bla: ", replace("a","b",$myvar),"\n";
有没有这样的
replace
Perl 中的函数,还是其他方法? s/
在这种情况下不会直接工作,我想避免使用辅助变量。有什么办法可以在线进行吗?
最佳答案
require 5.013002; # or better: use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";
见 perl5132delta :
The substitution operator now supports a
/r
option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.
my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'
关于regex - Perl:使用 s/(替换)并返回新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3440363/