Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^3: trim leading & trailing whitespace

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


in reply to Re^2: trim leading & trailing whitespace
in thread trim leading & trailing whitespace

$_ = " 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.


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

    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

Re^4: trim leading & trailing whitespace
by tlm (Prior) on Mar 30, 2005 at 10:41 UTC

    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

      Danger, don't use \b if you want to detect the edges between spaces an nonspaces. It won't work for nonspace+nonword characters, like quotes and punctuation.

      Perhaps replace the \b(.*?) with (\S.*?).

      Still, you're not running this with warnings enabled, are you? Both $1 and $2 are optional, so both can be undef, but you use their value regardless. This runs without warnings:

      s/^\s*?((?:\S.*?)?)\s*?(\n?)$/$1$2/gm;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2015-07-04 01:49 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 (57 votes), past polls