Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: trim leading & trailing whitespace

by jmcnamara (Monsignor)
on Mar 30, 2005 at 10:36 UTC ( #443400=note: print w/replies, xml ) Need Help??

in reply to trim leading & trailing whitespace

See perlfaq4 How do I strip blank space from the beginning/end of a string?.

It also say says that the s/^\s*(.*?)\s*$/$1/ construct is "unnecessarily slow and destructive". Benchmarks anyone?

See also trim() magic


Replies are listed 'Best First'.
Re^2: trim leading & trailing whitespace (Benchmark)
by Anonymous Monk on Mar 30, 2005 at 11:11 UTC
    Here's a benchmark, using the mentioned single regex, the double regex from the FAQ (also mentioned), BrowserUKs solution, and the one from Regexp::Common:
    #!/usr/bin/perl use strict; use warnings; use Benchmark 'cmpthese'; use Regexp::Common; use Test::More tests => 4; our @data = ( " White space in front", "White space at back ", "Nowhitespaceatall", "White space, but not in front or at back", " White space in front, and at back " ); our @expected = ( "White space in front", "White space at back", "Nowhitespaceatall", "White space, but not in front or at back", "White space in front, and at back" ); our (@s, @d, @b, @r); print '#'; cmpthese -1, { '#single' => '@s = @data; s/^\s*(.*?)\s*$/$1/s for @s', '#duo' => '@d = @data; s/^\s+//, s/\s+$// for @d', '#browseruk' => '@b = @data; s/^\s*(.*)\b\s*$/$1/s for @b', '#R::C' => '@r = map {$RE{ws}{crop}->subs($_)} @data', }; is_deeply (\@s, \@expected, "single"); is_deeply (\@d, \@expected, "duo"); is_deeply (\@b, \@expected, "browseruk"); is_deeply (\@r, \@expected, "R::C"); __END__ 1..4 # Rate #R::C #single #browseruk #duo #R::C 1914/s -- -87% -94% -97% #single 15175/s 693% -- -53% -75% #browseruk 32288/s 1587% 113% -- -46% #duo 59650/s 3017% 293% 85% -- ok 1 - single ok 2 - duo ok 3 - browseruk ok 4 - R::C

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://443400]
[Corion]: Discipulus: Yeah, a short vacation on the Canary islands (Lanzarote). Always great to be in the warmth and sun, from a cold and rainy February here ;)
[Corion]: choroba: Yeah, you have to find a time for the regular skype (or whatever) meetup, I imagine that's hard
[choroba]: Lanzarote is great!
choroba went there year ago
[Discipulus]: here spring has sprung, so the warm is available without holidays..

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2017-02-22 08:49 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (325 votes). Check out past polls.