substr vs regex

Ovid publiustemp-londonpm at
Mon Sep 3 11:22:48 BST 2007

--- alex at wrote:

> Imagine, say, someone wanted the last three characters of a string.
> They
> might use a regex /(...)$/ or substr($variable, -3)
> personally I recommend the former because it is more readable, but
> others
> have recommended substr to because you "dont need to bring out the
> big
> guns". (However no one could actually remember the substr function)
> Is one of these significantly more efficient than the other? Ok ok,
> so I
> could probably write a test in a few minutes but asking you guys is
> more
> interesting.

Define "efficient".  The definition varies tremendously depending on
your needs.  Optimization order:

1.  Correctness.
2.  Readability.
217.  Performance :)

It's far more important that your code be correct and legible than
fast. When you have the first two in place, don't worry about speed if
it's fast enough.  If it's not, then you can benchmark and find out
where it's *really* slow (and I doubt it will be a 'regex' versus
'substr' issue).


Buy the book  -
Perl and CGI  -
Personal blog -
Tech blog     -

More information about the mailing list