$line = qq{10 PRINT "<29>This should be dim.<30>EThis should be reversed.<28>This is bold."}; my %fix = ( "<29>" => '";@(-38);"', "<28>" => '";@(-40);"', "<27>" => '";@(-35);"', "<30>" => "<30>", ); $line =~ s/"([^"]*)"/my $s = $1;$s =~ s{(<\d+>)}{$fix{$1}}g;'"'.$s.'"'/ge; #or # $line =~ s/("[^"]*")/my $s = $1;$s =~ s{(<\d+>)}{$fix{$1}}g;$s/ge;