Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Regular Expressions

Remove leading and trailing white space from a string by KevinADC
Posted: 3 Feb 07 (Edited 15 Feb 07)

ignore this section:


This common task is best done using two regular expressions:


my $string = '  Mary had a little lamb.  ';
$string =~ s/^\s+//; #remove leading spaces
$string =~ s/\s+$//; #remove trailing spaces
print $string;

or as a stand alone function:


my $string = '  Mary had a little lamb.  ';
$string = rem_spaces($string);
print $string;

sub rem_spaces {
   my $t = shift || return(0);
   $t =~ s/^\s+//; #remove leading spaces
   $t =~ s/\s+$//; #remove trailing spaces
   return $string;

You might be tempted to write one regexp:


$string =~ s/^\s+([\s\S]+)\s+$/$1/;

or something similar, but this is invariably much slower.

Back to Perl FAQ Index
Back to Perl Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close