This program will perform 1000000 string replace operations and print the number of seconds it takes to complete each. Testing string replace method #1. Replace 'H' --> 'X' 0 second(s) Replace 'Hello' --> 'XX' 0 second(s) Replace 'Hello' --> '' 1 second(s) Replace 'Hel' --> 'XXXXXX' 14 second(s) Replace 'HelloWorld' --> 'XXXXXXXXXXXXX' 14 second(s) Testing string replace method #2. Replace 'H' --> 'X' 5 second(s) Replace 'Hello' --> 'XX' 2 second(s) Replace 'Hello' --> '' 1 second(s) Replace 'Hel' --> 'XXXXXX' 16 second(s) Replace 'HelloWorld' --> 'XXXXXXXXXXXXX' 1 second(s) Testing string replace method #3. Replace 'H' --> 'X' 1 second(s) Replace 'Hello' --> 'XX' 4928 second(s) Replace 'Hello' --> '' ################################################## #PROGRAM STARTS HERE: use strict; use warnings; # See: # http://www.perlmonks.org/?node_id=98357 my $T; my $str; my $find = ""; my $replace = ""; my $REPEAT = 1000000; my $METHOD = 1; print "This program will perform $REPEAT string replace operations\n"; print "and print the number of seconds it takes to complete each.\n"; # RUN TESTS for ($METHOD = 1; $METHOD <= 3; $METHOD++) { print "\nTesting string replace method #$METHOD.\n"; RunTest("H", "X"); RunTest("Hello", "XX"); RunTest("Hello", ""); RunTest("Hel", "XXXXXX"); RunTest("HelloWorld", "XXXXXXXXXXXXX"); } ##################################### sub RunTest { if (@_ != 2) {return;} ($find, $replace) = @_; $| = 1; # Disable buffering $str = 'HelloWorld' x $REPEAT; my $PADDING1 = ' ' x (13 - length($find)); my $PADDING2 = ' ' x (13 - length($replace)); print "Replace '$find'$PADDING1--> '$replace'$PADDING2"; # This method was suggested by tachyon. if ($METHOD == 1) { $find = quotemeta $find; # escape regex metachars if present $T = time; # measure time at the start. $str =~ s/$find/$replace/g; printTime(); # measure time at the end. } # This method was suggested by harangzsolt33 if ($METHOD == 2) { $T = time; # measure time at the start. $str = join( $replace, split($find, $str) ); printTime(); # measure time at the end. } # This method was suggested by davorg. if ($METHOD == 3) { $T = time; # measure time at the start. my $pos = index($str, $find); while ( $pos > -1 ) { substr( $str, $pos, length( $find ), $replace ); $pos = index( $str, $find, $pos + length( $replace )); } printTime(); # measure time at the end. } return; } ########################### sub printTime { my $DIFF = (time - $T); my $PADDING = ' ' x (3 - length($DIFF)); print "$PADDING $DIFF second(s)\n"; } ###########################