#! /usr/local/bin/perl use strict; use warnings; my $str = "word1, word2, #18abcdefgh ,word4, #24qwer, word5"; print "Before: $str\n"; while($str =~ m/(.*?)#(\d)(\d)(.*)/) { $str = $1 . "" . substr($4, $3); } print "After: $str\n"; #### Before: word1, word2, #18abcdefgh ,word4, #24qwer, word5 After: word1, word2, ,word4, , word5 #### #! /usr/local/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $str = "word1, word2, #18abcdefgh ,word4, #24qwer, word5"; print "Before: $str\n"; while($str =~ m/#(\d)(\d)/g) { substr($str, pos($str) - 3, $2 + 3, ""); } print "After: $str\n"; my $start = "word1, word2, #18abcdefgh ,word4, #24qwer, word5"; print "\n\n"; cmpthese( -10, { 're-match whole string' => sub { my $str = $start; while($str =~ m/(.*?)#(\d)(\d)(.*)/) { $str = $1 . "" . substr($4, $3); } }, 'match #\d\d' => sub { my $str = $start; while($str =~ m/#(\d)(\d)/g) { substr($str, pos($str) - 3, $2 + 3, ""); } }, }, ); #### Before: word1, word2, #18abcdefgh ,word4, #24qwer, word5 After: word1, word2, ,word4, , word5 Rate re-match whole string match #\d\d re-match whole string 75230/s -- -28% match #\d\d 104315/s 39% --