Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: Strip leading and trailing blanks
by fruiture (Curate) on Jul 29, 2003 at 21:16 UTC

    Because this is a common problem (and _has_ been answered here before) i can tell that there is a very efficient way to do it (probably the most efficient one of the less complicated):

    s/^\s+//; s/\s+$//;

    See perlop and perlre.

    --
    http://fruiture.de

      Check out trim() by japhy... a really neat sub that wraps and builds upon this very solution.

          --k.


Re: Strip leading and trailing blanks
by arthas (Hermit) on Jul 29, 2003 at 22:45 UTC
Re: Strip leading and trailing blanks
by runrig (Abbot) on Jul 29, 2003 at 22:34 UTC
    (maybe) Not quite as efficient as the two-step method already mentioned, but this works:
    $name =~ s/^\s+|\s+$//g;
    Update: typo caught by Hofmator, fixed.
Re: Strip leading and trailing blanks
by snax (Hermit) on Jul 30, 2003 at 16:18 UTC
    TIMTOWTDI :)

    I've always been fond of this, which also compresses "extra" spaces in the middle to a single space:

    $name = join ' ', split ' ', $name;
    It's not all that much slower than the others, and if you want to compress the internal whitespace it's hard to beat. Lots of my proggies have a little sub:
    sub wsp { $_ = shift; join ' ', split; }
    which takes advantage (in terseness, not speed) of the magic of $_ and split's default behavior.
Re: Strip leading and trailing blanks
by Anonymous Monk on Jul 30, 2003 at 13:06 UTC
    Wow, thanks everyone. I learned something from each reply. This is a great site.