To LUGNET HomepageTo LUGNET News HomepageTo LUGNET Guide Homepage
 Help on Searching
 
Post new message to lugnet.off-topic.geekOpen lugnet.off-topic.geek in your NNTP NewsreaderTo LUGNET News Traffic PageSign In (Members)
 Off-Topic / Geek / 2239
2238  |  2240
Subject: 
Re: Strip surplus white space with Perl
Newsgroups: 
lugnet.off-topic.geek
Date: 
Sun, 29 Oct 2000 18:14:55 GMT
Viewed: 
149 times
  
In lugnet.off-topic.geek, Fredrik Glöckner writes:
Hi, I'm looking into a quick and simple way to strip off all surplus
white space from a string with Perl.  If two consecutive characters
are <SPACE> and <RET>, for example, it doesn't matter to me which one
is preserved and which one is chopped off.  Any suggestions?

First, if you want to trim any leading and trailing whitespace, this'll do it:

   $foo =~ s/^\s+//;
   $foo =~ s/\s+$//;

Then, if you need to preserve the first whitespace character and throw out
the rest:

   $foo =~ s/(\s)\s+/$1/g;

Or, if spaces (ASCII 32) are always OK in the output string, this is simpler
and marginally faster:

   $foo =~ s/\s{2,}/ /g;

Or, if you don't care about speed or memory usage, you could use split and
join:

   $foo = join " ", split /\s+/, $foo;


Yes, I am a Perl novice... :-)

If you'll be learning more Perl, check these out:

   http://www.oreilly.com/catalog/lperl2/
   http://www.oreilly.com/catalog/pperl3/

And if you'll be using it a lot, but not wanting to learn much, this might be
of help (it's also helpful if you want to learn more too):

   http://www.oreilly.com/catalog/cookbook/

And this is an absolutely outstanding book on regexen:

   http://www.oreilly.com/catalog/regex/

And there are at least two excellent non-O'Reilly Perl books too:

   http://www.effectiveperl.com/
   http://www.manning.com/Conway/

HTH,
--Todd



Message is in Reply To:
  Strip surplus white space with Perl
 
Hi, I'm looking into a quick and simple way to strip off all surplus white space from a string with Perl. If two consecutive characters are <SPACE> and <RET>, for example, it doesn't matter to me which one is preserved and which one is chopped off. (...) (24 years ago, 29-Oct-00, to lugnet.off-topic.geek)

10 Messages in This Thread:



Entire Thread on One Page:
Nested:  All | Brief | Compact | Dots
Linear:  All | Brief | Compact
    

Custom Search

©2005 LUGNET. All rights reserved. - hosted by steinbruch.info GbR