Perl:使用 s/(替换)并返回新字符串 [英] Perl: Use s/ (replace) and return new string

查看:26
本文介绍了Perl:使用 s/(替换)并返回新字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中,运算符 s/ 用于替换字符串的一部分.现在 s/ 将改变它的参数(字符串).但是,我想在打印之前替换字符串的一部分,如

In Perl, the operator s/ is used to replace parts of a string. Now s/ will alter its parameter (the string) in place. I would however like to replace parts of a string befor printing it, as in

print "bla: ", replace("a","b",$myvar),"
";

Perl 中是否有这样的 replace 函数,或者其他方法?s/ 在这种情况下不会直接工作,我想避免使用辅助变量.有什么方法可以在线执行此操作吗?

Is there such replace function in Perl, or some other way to do it? s/ will not work directly in this case, and I'd like to avoid using a helper variable. Is there some way to do this in-line?

推荐答案

require 5.013002; # or better:    use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "
";

参见 perl5132delta:

替换运算符现在支持 /r 选项,该选项复制输入变量,对副本执行替换并返回结果.原件保持不变.

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'

这篇关于Perl:使用 s/(替换)并返回新字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆