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+$//; } #### use Benchmark; timethese(500_000, { one => sub { my $foo = " perl monks "; $foo =~ s/^\s+|\s+$//g; }, two => sub { my $foo = " perl monks "; for ($foo) { s/^\s+//; s/\s+$//; } }, }); #### Benchmark: timing 500000 iterations of one, two... one: 11 secs (11.75 usr 0.00 sys = 11.75 cpu) two: 8 secs ( 7.57 usr 0.00 sys = 7.57 cpu)