#!/usr/local/bin/perl -w use strict; my $s = "Terence and Philip are sweet\n"; my $c = 'e'; my $r = 1; my $n = 3; sub mine { my ($str,$chr,$new,$nbr)=@_; my $reg="(.+?)$chr" x $nbr; $_=$str; (/$reg/)&&($str=$&)&&($_=$')&&(s/$chr/$new/g); return $str.$_; } sub bbfus { my ($str, $chr, $rep, $nth) = @_; my $pos = 0; $pos = index($str, $chr, $pos+1) for(1..$nth); substr($str, $pos) =~ s/$chr/$rep/g; return $str; } sub quents { my ($str, $chr, $rep, $nth) = @_; my $i = 1; $str =~ s/($chr)/$i++<$nth?$1:$rep/eg; return $str; } use Benchmark qw( timethese cmpthese ); cmpthese(500000, { "BBFU'S" => sub { bbfus ($s, $c, $r, $n) }, "Quent's" => sub { quents ($s, $c, $r, $n) }, "MINE" => sub { mine ($s,$c,$r,$n) }, });