加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:34:04 所属栏目:百科 来源:网络整理
导读:在Perl中,操作符s /用于替换字符串的部分。现在s /将改变它的参数(字符串)到位。然而,我想替换打印它的字符串的部分,如同 print "bla: ",replace("a","b",$myvar),"n"; 有没有这样的替换功能在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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读