Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: trim leading & trailing whitespace

by bart (Canon)
on Mar 30, 2005 at 09:22 UTC ( #443386=note: print w/ replies, xml ) Need Help??


in reply to trim leading & trailing whitespace

Multiline, huh? You mean you want to trim every line independently?

s/^[\t\ ]+//gm; s/[\t\ ]+$//gm;
I don't use \s because I want to leave the newlines alone.


Comment on Re: trim leading & trailing whitespace
Download Code
Re^2: trim leading & trailing whitespace
by thinker (Parson) on Mar 30, 2005 at 10:04 UTC

    Hi bart

    In the example I gave above,

     s/^\s*(.*?)\s*$/$1/gm

    the combination of the \m modifier, and the line anchors ^ and $ will ensure the newlines are left alone

    cheers

    thinker

      $_ = " no \n \n \n they \n \n won't \n\n\n"; s/^\s*(.*?)\s*$/$1/gm; print;
      Result:
      no
      they
      won't
      

      All blank lines are gone.

        Hi bart,

        I see what you mean now. I thought you were suggesting it would remove the newline characters, not just the blank lines. Your way is more correct.

        cheers

        thinker

        How about this:

        $_ = " yes \n \n \n they \n \n will \n\n\n"; s/^\s*?(?:\b(.*?)\s*?)?(\n)?$/$1$2/gm; print; __END__ % perl 443391.pl yes they will

        the lowliest monk

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2015-07-03 02:41 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 (47 votes), past polls