Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: trim leading & trailing whitespace

by brian_d_foy (Abbot)
on Mar 31, 2005 at 19:37 UTC ( #443942=note: print w/ replies, xml ) Need Help??


in reply to trim leading & trailing whitespace

I'm surprised that everyone (including the FAQ) missed the most obvious solution which uses an alternation. Most other solutions seem to forget that the $ anchor is right before the trailing newline. :)

$string =~ s/^\s+|\s+$//gm;

If you want to preserve blank lines, it's a tiny bit longer.

s/^[\t\f ]+|[\t\f ]+$//mg;

Remember: in Perl, the common things are supposed to be easy, so if you're doing something common and it's not easy, you're probably missing something. :)

I'm going to update the FAQ answer too.

--
brian d foy <brian@stonehenge.com>


Comment on Re: trim leading & trailing whitespace
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://443942]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2015-07-05 22:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (68 votes), past polls