in reply to How to introduce a frustrating bug with a single whitespace

The lesson? I probably should have used Text::Trim. :)

It could be, but I would say the lesson is to not try to do it all in one step. I remember reading a Randal Schwartz rant some time back about people continually trying to do whitespace trimming in one step, when it's much simpler and straight-forward to do it in two:

$user =~ s/^\s+//s; $user =~ s/\s+$//s;
I think you'll find that that runs much faster than one regexp involving alternation....

Replies are listed 'Best First'.
Re^2: How to introduce a frustrating bug with a single whitespace
by radiantmatrix (Parson) on Jan 17, 2008 at 21:16 UTC

    I think you'll find that that runs much faster than one regexp involving alternation....

    Well, I don't really care much about faster runtimes -- most of what I do waits on disk access and network I/O long before it runs into RAM or CPU limits, so which regex is fastest almost never comes into play.

    I try to write primarily for readability. I realize, of course, that "readability" is subjective. But, I find s{^\s+|\s+$}{}g to be more readable than the two-line alternative. When I see that one line, I immediately think "ok, trim whitespace from the ends". When I see the two, I have to stop and think about it. Just me.

    One of the things I like about Python1 is the readability of performing this action:

    text = " a string of some sort, with space at either end " text = text.strip()

    I think that's what draws me to Text::Trim (if I have to do the step repeatedly, especially):

    my $text = " a string of some sort, with space at either end "; $text = trim( $text );

    Of course, creating a dependency for something like that seems a little excessive, so I've recently taken to

    my $TRIM_WHITESPACE_RE = qr/^\s+|\s+$/ ## ... later on .. ## $text =~ s/$TRIME_WHITESPACE_RE//g;

    1: I know, I know. :) Seriously, though, Python has some nifty things in it, even if I still like Perl better.

    <radiant.matrix>
    Ramblings and references
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet