2016-01-04 20 views
3

假設我有一個字符串,數組如下:如何與多發性值替換字符串中的Perl

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

那麼,有沒有更好的方式來迅速與每個值數組中替換字符串,而不是使用for循環,並將每個替換的輸出放入新數組中。

我預計產量爲:

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

你是不是指'my $ str [i] =「currenttring」;'? –

+1

如果你可以自己設置字符串標記,那麼你可以使用sprintf:'my $ str =「currentString%s」;我的@output = map {sprintf $ str,$ _} @ arr'。 – TLP

+0

@TLP謝謝!我正在使用只是爲了一個字符的含義需要被替換! –

回答

2

不使用循環使用map爲做到這一點

/R用於返回替代的非破壞性修改並保持原來的字符串未觸及

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" 
+0

這樣就會產生'{「currentStringwithKey 1」,「currentStringwithKey 2」}',不完全是要求的。 OP想要用數字替換文本''。 –

+0

編輯完成後就可以了。但是,如果''還沒有結束呢? '$ str'的​​值是一個_template_,''是一個佔位符。 –

+1

感謝@mkHun,那就是我要找的 –

2

這裏有你想要的。這種做法將與替換文本替換<i>無論在哪裏<i>出現在模板$str

@outputArray = map { my $i=$str; $i =~ s/\<i\>/$_/; $i } @arr 

您需要$str複製到一個臨時取代,因爲在原地工作。如果您直接使用$str,那麼其價值將首次發生變化。

+0

正則表達式中的'r'標誌可以讓你更乾淨地做到這一點。 – Sobrique

+2

只要使用'map {$ str =〜s//$ _/r}'就可以。不需要臨時變量或轉義'<' and '>'。 –