Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Strip leading and trailing blanks

by Anonymous Monk
on Jul 29, 2003 at 21:10 UTC ( [id://278991]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://278991]
Approved by Paladin
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-25 16:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found