Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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

by faq_monk (Initiate)
on Oct 08, 1999 at 00:20 UTC ( #602=perlfaq nodetype: print w/ replies, xml ) Need Help??

Current Perl documentation can be found at

Here is our local, out-dated (pre-5.6) version:

Although the simplest approach would seem to be:

    $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:

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

Or more nicely written as:

    for ($string) {

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:

    # trim whitespace in the scalar, the array, 
    # and all the values in the hash
    foreach ($scalar, @array, @hash{keys %hash}) {

Log In?

What's my password?
Create A New User
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: (11)
As of 2015-11-30 16:10 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (777 votes), past polls