Perl FAQ 4.33: Is there any easy way to strip blank space from the beginning/end of

Perl FAQ 4.33

Is there any easy way to strip blank space from the beginning/end of

a string?

Yes, there is. Using the substitution command, you can match the blanks and replace it with nothing. For example, if you have the string " String " you can use this:

    s/^\s*(.*?)\s*$/$1/;    # perl5 only!

    s/^\s+|\s+$//g;         # perl4 or perl5

or even

    s/^\s+//; s/\s+$//;

Note however that Jeffrey Friedl* says these are only good for shortish strings. For longer strings, and worse-case scenarios, they tend to break-down and become inefficient.

For the longer strings, he suggests using either

    $_ = $1 if m/^\s*((.*\S)?)/;
or
    s/^\s*((.*\S)?)\s*$/$1/;

It should also be noted that for generally nice strings, these tend to be noticably slower than the simple ones above. It is suggested that you use whichever one will fit your situation best, understanding that the first examples will work in roughly ever situation known even if slow at times.


Other resources at this site: