I needed to strip whitespace off both ends of a string and played around with ways of doing it. Can it be done faster than any of these functions:
# No taint implications. sub A { s/^\s*//; s/\s*$//; return $_; } # These untaint the return value. sub B { m/^\s*(.*\S)\s*$/; return $1; } sub C { m/(\S+.*\S*)/; return $1; } sub D { m/(\S?.*\S*)/; return $1; }

I tend to use A as it does not untaint the string due to selecting $1.

Bench marks and complete code follow:

Rate A B C D A 4709/s -- -34% -39% -44% B 7091/s 51% -- -8% -16% C 7680/s 63% 8% -- -9% D 8449/s 79% 19% 10% --

Code is:

use strict; use warnings; use Benchmark qw(cmpthese); # No taint implications. sub A { s/^\s*//; s/\s*$//; return $_; } # These untaint the return value. sub B { m/^\s*(.*\S)\s*$/; return $1; } sub C { m/(\S+.*\S*)/; return $1; } sub D { m/(\S?.*\S*)/; return $1; } my @data = ( 'hello', ' hello', ' hello ', 'hello hello', ' hello hello', 'hello hello ', ' hello hello', ' hello hello ', 'h', ' h', 'h ', ' h ', "\n\t hello \n\t" ); for (@data) { my $A = A( $_ ); my $B = B( $_ ); my $C = C( $_ ); my $D = D( $_ ); unless ( $A eq $B && $A eq $C && $A eq $D ) { warn "Found a disagreement\n"; warn "\tA is '$A'\n\tB is '$B'\n\tC is '$C'\n\tD is '$D'\n\n"; } if ( $A =~ m/(^\s|\s$)/ ) { warn "Regexp not working\n\tA is '$A'\n\n"; } } cmpthese( -3, { A => sub { for (@data) { A( $_ ); }}, B => sub { for (@data) { B( $_ ); }}, C => sub { for (@data) { C( $_ ); }}, D => sub { for (@data) { D( $_ ); }}, });

--tidiness is the memory loss of environmental mnemonics


In reply to Fastest (Golfish) way to strip whitspace off ends. by EvdB

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.