in reply to remove both leading and trailing spaces

Another alternative:
$val =~ s/^\s*(.*?)\s*$/$1/;

Replies are listed 'Best First'.
Re: Re: remove both leading and trailing spaces
by flounder99 (Friar) on Sep 26, 2003 at 14:47 UTC
    That was my first thought also. I was just curious if it was faster than s/^\s+|\s+$//g;
    use Benchmark; my $val = " Smart Way "; timethese(1000000, { regex1 => sub { my $tmp = $val; $tmp =~ s/^\s*(.*?)\s*$/$1/g; }, regex2 => sub { my $tmp = $val; $tmp =~ s/^\s+//; $tmp =~ s/\s+$//; } }); __OUTPUT__ Benchmark: timing 1000000 iterations of regex1, regex2... regex1: 8 wallclock secs ( 8.10 usr + 0.00 sys = 8.10 CPU) @ 12 +3426.31/s (n=1000000) regex2: 2 wallclock secs ( 1.96 usr + 0.00 sys = 1.96 CPU) @ 50 +9164.97/s (n=1000000)

    --

    flounder