in reply to Re: Re: remove both leading and trailing spaces
in thread remove both leading and trailing spaces

#!/usr/bin/perl -w use strict; use Benchmark; my $val=" Smart Way "; timethese(1000000, { regex1 => sub { my $tmp = $val; $tmp =~ s/^\s*(.*?)\s*$/$1/g; }, regex2 => sub { my $tmp = $val; $val = join (" ",split " ",$val); }, regex3 => sub { my $tmp = $val; $tmp =~ s/^\s+//; $tmp =~ s/\s+$//; } });

__OUTPUT__
Benchmark: timing 1000000 iterations of regex1, regex2, regex3...
regex1: 6 wallclock secs ( 5.25 usr + 0.00 sys = 5.25 CPU) @ 190512.48/s (n=1000000)
regex2: 2 wallclock secs ( 1.83 usr + 0.00 sys = 1.83 CPU) @ 547045.95/s (n=1000000)
regex3: 2 wallclock secs ( 1.02 usr + 0.00 sys = 1.02 CPU) @ 984251.97/s (n=1000000)

Replies are listed 'Best First'.
Re: Re: Re: Re: remove both leading and trailing spaces
by the_0ne (Pilgrim) on Sep 26, 2003 at 20:46 UTC
    One thing you want to watch with regex2...
    regex2 => sub { my $tmp = $val; $val = join (" ",split " ",$val); },
    ... is if the variable has spaces contained in the phrase that you want to keep, this will get rid of them...
    $var = " Smart Way "; $val = join (" ",split " ",$val); print "var: $var\n"; # $var now "Smart Way", internal spaces gone.
    regex1 and regex2 would retain the internal spaces.