如何用多个值替换perl中的字符串

How to replace string in perl with mutiple value

假设我有一个字符串和一个数组如下:

my $str = "currentStringwithKey<i>";
my @arr = ("1", "2");

那么,有没有更好的方法可以快速用数组中的每个值替换字符串,而不是使用 for 循环,并将每个替换的输出放入新数组中。

我的预期输出是:

my @outputArray = ("currentStringwithKey1", "currentStringwithKey2");

不使用 for 循环使用 map for 来完成它

/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"

这就是你想要的。无论 <i> 在模板 $str

中出现的位置如何,此方法都将用替换文本替换 <i>
@outputArray  = map { my $i=$str; $i =~ s/\<i\>/$_/; $i } @arr

您需要将 $str 复制到临时文件,因为替换工作 in-place。如果你直接使用$str那么它的值会在第一次被改变。