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: Frequently Asked Questions:
How do I strip blank space from the beginning/end

 



Jasmine
Administrator

Jan 19, 2001, 2:56 PM

Post #1 of 1 (1663 views)
How do I strip blank space from the beginning/end Can't Post

(From the Perl FAQ)

How do I strip blank space from the beginning/end of a string?

Although the simplest approach would seem to be:

Code
    $string =~ s/^\s*(.*?)\s*$/$1/;

This is unneccesarily slow, destructive, and fails with embedded newlines. It is much better faster to do this in two steps:

Code
    $string =~ s/^\s+//; 
$string =~ s/\s+$//;

Or more nicely written as:

Code
    for ($string) { 
s/^\s+//;
s/\s+$//;
}

This idiom takes advantage of the foreach loop's aliasing behavior to factor out common code. You can do this on several strings at once, or arrays, or even the values of a hash if you use a slide:

Code
    # trim whitespace in the scalar, the array,  
# and all the values in the hash
foreach ($scalar, @array, @hash{keys %hash}) {
s/^\s+//;
s/\s+$//;
}


 
 


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

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