CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
remove whitespace

 



inlimbo
User

Jan 17, 2005, 5:28 PM

Post #1 of 4 (3307 views)
remove whitespace Can't Post

How do I change a block of text:

my $text = "The quick brown
fox jumped over
the lazy
dog";

into a single line:

$text = "The quick brown fox jumped over the lazy dog";


KevinR
Veteran


Jan 17, 2005, 11:08 PM

Post #2 of 4 (3300 views)
Re: [inlimbo] remove whitespace [In reply to] Can't Post

lets look at what you have:

The quick brown
fox jumped over
the lazy
dog

with the hidden characters exposed it can be simulated like this:

The\squick\sbrown\n
fox\sjumped\sover\n
the\slazy\n
dog"

\s is a space
\n is a newline

what you want to do is replace the newlines with a space, which can be done like this:

$line =~ s/\n/\s/g;

The "g" option tells perl to replace all occurances of the pattern in the string.

if its a windows file you may need to use:

$line =~ s/\r\n/\s/g;

or to cover both Unix and Windows style newlines:

$line =~ s/\r?\n/\s/g;
-------------------------------------------------


(This post was edited by KevinR on Jan 17, 2005, 11:10 PM)


davorg
Thaumaturge / Moderator

Jan 19, 2005, 2:16 AM

Post #3 of 4 (3286 views)
Re: [KevinR] remove whitespace [In reply to] Can't Post

You can't use \s in the replacement expression in the substitution operator. Escapes like \s only have a meaning in a regular expression.

Under my current version of Perl (5.8.0) I get this error:


Code
$ ./white.pl 
Unrecognized escape \s passed through at ./white.pl line 11.
The quick brownsfox jumped oversthe lazysdog


So it's ignoring the \s and replacing newlines with the empty string.

Try this instead:


Code
$text =~ s/\n/ /g;


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


KevinR
Veteran


Jan 19, 2005, 3:38 PM

Post #4 of 4 (3277 views)
Re: [davorg] remove whitespace [In reply to] Can't Post

my $bad = 'DOH!';

thanks again Dave!
-------------------------------------------------

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives