perl -wMstrict -le "{ my %emphasis; my $word = qr{ (\b \w+ \b) }xms; sub emphasize { my $string = shift; %emphasis = map { $_ => 0 } @_; my $intro = qq{@{[ sort { $a <=> $b } keys %emphasis ]}}; my $words = 0; $string =~ s{ ($word) } { exists $emphasis{++$words} ? qq{**$1**} : $1 }xmsge; return qq{$intro $string}; } } my $string = 'Sam goes to school to play football.'; print emphasize($string, 4, 7); print emphasize($string, 7, 2, 4); print emphasize($string); print emphasize('the cow jumped over the', 3, 4, 1); " 4 7 Sam goes to **school** to play **football**. 2 4 7 Sam **goes** to **school** to play **football**. Sam goes to school to play football. 1 3 4 **the** cow **jumped** **over** the