假设我有一个字符串和一个数组,如下所示:
my $str = "currentStringwithKey<i>";
my @arr = ("1", "2");
那么,有没有更好的方法可以快速将字符串替换为数组中的每个值,而不是使用 for 循环,并将每个替换的输出放入新数组中。
我的预期输出是:
my @outputArray = ("currentStringwithKey1", "currentStringwithKey2");
最佳答案
不使用for循环使用map为了做到这一点
/r is the non-destructive modifier used to Return substitution and leave the original string untouched
my $str = "currentStringwithKey<i>";
my @arr = ("1", "2");
my @output = map{ $str=~s/<i>/$_/rg } @arr;
#$str not to be changed because of the r modifier
print @output;
然后@output
数组包含这样的
$output[0] = "currentStringwithKey1",
$output[1] = "currentStringwithKey2"
关于string - 如何用多个值替换perl中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584483/