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

标签 string perl replace str-replace

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

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/

相关文章:

delphi - Delphi中是否需要将字符串转换为WideString?

linux - 为 mod_perl 更改 perl

php - 替换mysql中的单个字母

string - 读取字符串时如何匹配 float

javascript - 字符串连接不起作用,抛出错误

java - 在 Java 中,如何将 XML 解析为字符串而不是文件?

javascript - 如何通过 perl 中的 ajax 调用将值从一个 div 传递到另一个?

Perl LDAP 搜索 - 群组中超过 1500 名成员

file - 使用 AppleScript 在文本文件中查找和替换

JavaScript 正则表达式 : find GUID in an URL and replace it