循环全局替换 [英] Loop through global substitution
本文介绍了循环全局替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$num = 6;
$str = "1 2 3 4";
while ($str =~ s/\d/$num/g)
{
print $str, "\n";
$num++;
}
是否可以在 perl 中执行上述操作?我希望循环只运行 4 次,并以 $str
为 6 7 8 9
结束.
Is it possible to do something like the above in perl? I would like the loop to run only 4 times and to finish with $str
being 6 7 8 9
.
推荐答案
您不需要循环:/g 修饰符会导致替换重复进行多次匹配.您想要的是/e 修饰符来计算替换.假设你得到的效果是每个数字加5,示例代码如下.
You don't need the loop: the /g modifier causes the substitution to be repeated as many times as it matches. What you want is the /e modifier to compute the substitution. Assuming the effect you were after is to add 5 to each number, the example code is as follows.
$str = "1 2 3 4";
$str =~ s/(\d)/$1+5/eg;
print "$str\n";
如果您真的想替换以 6 开头的数字,那么这行得通.
If you really wanted to substitute numbers starting with 6, then this works.
$num = 6;
$str = "1 2 3 4";
$str =~ s/\d/$num++/eg;
print "$str\n";
这篇关于循环全局替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文