Regex Search and Replace Efficiency in Perl

Album Cover: First Impressions of Earth

"Don't be a coconut. God is trying to talk to you."
The Strokes / Ask Me Anything

Posted on June 04, 2008 7:37 PM in Programming
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

While researching a simple string operation (removing white space from the beginning and end of a string) in Perl this evening, I stumbled across an interesting tidbit regarding the performance of regular expression search and replace in the Tek-Tips Forums.

It turns out that trimming leading and trailing white space using two separate search and replace calls, like so:

$var =~ s/^\s+//;
$var =~ s/\s+$//;

...is much more efficient than using a single call, like so:

$var =~ s/^\s+(.*?)\s+$/$1/;

Good to know!

Comments

Ian Clifton on June 04, 2008 at 8:59 PM:

That makes sense, though it isn't something that I would have considered. Of course, I was babied with functions like trim in PHP that prevented me from having to learn regular expressions back when I was first getting into web development.

Permalink

Bernie Zimmermann on June 04, 2008 at 9:30 PM:

Yeah, my "research" started out with "perl trim." ;)

Permalink

wgxsrrvs on May 15, 2017 at 5:23 AM:

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.

Name:

Email Address:

Website:

Comments:

Check this box if you hate spam.