split string into several substring using indexes

96 Views Asked by At

I have this string and hash:

Input data:

my $string = 'GATGCAGTTAGGCGTAGCAGAGTGAGACGACGACGATATTAGGACCCGGTAAGGCACAATATAGC';
my %coord_colors = (
  10 => "red",
  48 => "orange",
  60 => "purple",
);

What I want to do is to "open" the string at each hash key position, and insert the key-value. See the desired output to have an idea about what I'm trying to explain:

Desired output:

GATGCAGTTAredGGCGTAGCAGAGTGAGACGACGACGATATTAGGACCCGorangeGTAAGGCACAATpurpleATAGC

I know how the substr and split functions, but I'm not inspired about how to divide a string in several parts "simultaneously" and then introduce another string, and finally join. I've thought about doing a loop, and change positions in the has while I add the first positions but I would like to know the best approach to figure out this task.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use substr() as an lvalue and start replacing the string from right side of it,

my $string = 'GATGCAGTTAGGCGTAGCAGAGTGAGACGACGACGATATTAGGACCCGGTAAGGCACAATATAGC';
my %coord_colors = (
  10 => "red",
  48 => "orange",
  60 => "purple",
);

substr($string,$_,0) = $coord_colors{$_}
  for sort { $b <=> $a } keys %coord_colors;

print $string;

output

GATGCAGTTAredGGCGTAGCAGAGTGAGACGACGACGATATTAGGACCCGorangeGTAAGGCACAATpurpleATAGC

using regex,

$string =~ s|.{$_}\K|$coord_colors{$_}|s
  for sort { $b <=> $a } keys %coord_colors;