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

查看:529
本文介绍了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),"\n";

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, "\n";

请参见 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天全站免登陆