It is much better faster to do this in two steps: $string =~ s/^\s+//; $string =~ s/\s+$//; Or more nicely written as: for ($string) { s/^\s+//; s/\s+$//; }