in reply to trimming space from both sides of a string
|Replies are listed 'Best First'.|
Re^2: trimming space from both sides of a string
by perl-diddler (Chaplain) on Oct 24, 2010 at 23:56 UTC
I can't vouch for best speed in benchmarks, but works in any case I've needed such a construct for.
It certainly works, but it's interesting to see what happens under the covers.
If you use a regex that doesn't use captures:
You'll notice that the PV (the pointer to the memory holding the actual string) hasn't changed. Although the leading and trailing whitespace has been "removed", this has been done by juggling a few offsets into the original string.
Now doing it your way:
Notice that the PV changed, meaning that it had to: calculate the offset and length of the "remainder"; it then allocated a new lump of space to hold it; then copy it from the original string to the new string; and then free the old space.
And in the process, it upgraded the original PV to a PVMG and attached some magic to it, meaning several more allocations and frees. I'm not sure quite what that magic does in this case?
So, whilst the end result is semantically the same, the route getting there is a lot further around.
Sometimes, on a nice day, a slow, meandering route to the shops is a pleasant diversion, but few of would deliberately take a circuitous route habitually if we know a better one.
Of course, if you really want to "do it the right way", you'd replace these simple one liners with a CPAN module like Text::Trim which uses the more efficient two regex method. Of course, by doing so you'd be throwing away the performance gain of the two regex method by a) calling a subroutine; b) having that subroutine do inanities like assigning @_ to itself! (But only if it actually contains something!)
But hey. It's on CPAN, so it's got to be good right!
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.