Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace string in perl with mutiple value

Suppose I have a string, and an array as follow:

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

So, is there any better way to quickly replace the string with every value in the array, rather than using for loop, and put the output of each replacement into new array.

My expect output was:

my @outputArray = ("currentStringwithKey1", "currentStringwithKey2");
like image 327
Phuong Pham Avatar asked Sep 05 '25 23:09

Phuong Pham


1 Answers

Without using for loop use map for to do it

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

Then the @output array contain like this

$output[0] = "currentStringwithKey1",
$output[1] = "currentStringwithKey2"
like image 74
mkHun Avatar answered Sep 09 '25 00:09

mkHun