正则表达式 – Perl:使用s /(替换)并返回新的字符串

前端之家收集整理的这篇文章主要介绍了正则表达式 – Perl:使用s /(替换)并返回新的字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Perl中,操作符s /用于替换字符串的部分。现在s /将改变它的参数(字符串)到位。然而,我想替换打印它的字符串的部分,如同
print "bla: ",replace("a","b",$myvar),"\n";

有没有这样的替换功能在Perl,还是其他一些方法呢?在这种情况下,s /将不会直接工作,我想避免使用帮助变量。有没有办法这样做呢?

未经测试:
require 5.013002;
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'
原文链接:https://www.f2er.com/regex/357417.html

猜你在找的正则表达式相关文章