Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Re: Re: remove both leading and trailing spaces

by softworkz (Monk)
on Sep 26, 2003 at 16:52 UTC ( #294490=note: print w/replies, xml ) Need Help??

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

I find this way to be pretty fast on windoze, can someone benchmark it?
#!/usr/bin/perl -w use strict; my $val=" Smart Way "; $val = join (" ",split " ",$val); print '>'.$val.'<'; # shld give me >Smart Way<

Replies are listed 'Best First'.
Re: Re: Re: remove both leading and trailing spaces
by softworkz (Monk) on Sep 26, 2003 at 17:02 UTC
    #!/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+$//; } });

    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)
      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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://294490]
[LanX]: as long as he has votes left, the nodelet remains
[LanX]: There is a very simple solution ...
[marinersk]: Correct, so one workaround is to leave one vote.
[marinersk]: But I was looking for a more elegant solution. It appears noone online at this time is aware of one.
[LanX]: go to Nodelet Settings and click "All nodelets off"
[marinersk]: LanX++ LOL Yes, that is another workaround. :-)

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2017-05-29 14:17 GMT
Find Nodes?
    Voting Booth?