use strict; use warnings; my $sentence = 'Sam goes to school to play football.'; my @subs = ([12, 17], [27, 34]); my @counts; @subs = sort {$b->[0] <=> $a->[0]} @subs; # Descending sort by first char pos for my $sub (@subs) { unshift @counts, 1 + (substr $sentence, 0, $sub->[0]) =~ s/(\s+)/$1/g; substr $sentence, $_, 0, '**' for $sub->[1] + 1, $sub->[0]; } print "@counts $sentence\n"; #### 4 7 Sam goes to **school** to play **football**.