One candidate remains on our brain, the idea of using the substr function to grab the text in
question. Such a solution might look like:
=qq/filename.txt/; =substr (,index(,qq/./)+1);
In this approach, we use index to find the location of the decimal in the string, and then grab
the text starting one place to the right of the decimal, through to the end of the string. Again, to
use Benchmark; &Benchmark::timethis(500000, '=qq/filename.txt/; =substr (,index(,qq/./)+1)');
timethis 500000: 0 wallclock secs ( 0.65 usr + 0.00 sys = 0.65 CPU) @ 768049.16/s (n=500000)
Whoa, nelly! Indeed, the substr solution whooped the regular expression at nearly twice the
speed, and almost four times the speed of the split function. In all three of our cases, the code
was itself was quite simple. But exactly how Perl implements these different functions internally
– regular expressions, split, and substr – varies. While we shouldn’t draw across-the-board
conclusions from this test, we can draw the conclusion that for this particular case, the substr
function is much faster than the alternatives as measured across 500,000 iterations. Also,
ordering pizza tonight is probably a good idea, no matter how long it takes.
Apples to Apples, Oranges to Oranges
In learning to use Benchmark’s timethis function, we wound up comparing the speed of several
solutions. In fact, the Benchmark module provides a ready-made comparison function that can
make measurements of several solutions even simpler. This time, let’s imagine a case where
we want to code a subroutine that will accept a string value, and return a string value
consisting of the character codes for each character in the original string, separated by
For example, the string “A” would, when passed through this subroutine, be returned merely as
“65”. The string “AB” would be returned as “65 66”, and so on.
Once again, thanks to the versatility of Perl, we can let our imagination run wild – but not too
wild. Just wild enough, for now, to generate three plausible subroutines to solve this case.
The first, wordOrd_a, splits the incoming string into a list of letters, iterates through that list,
pushing the character code for each letter (via the ord function) onto a new list. Finally, it
returns a scalar by joining the elements of the new list.