I wrote some benchmark code to test the popular answers, and a method using just pattern match and capture instead of s///. I got good results from my pattern match, so I tried plugging my pattern into Daddio's solution (s-capture), and got a significant speedup of it (s-capture2), but still not as good as just using m//.
use Benchmark 'cmpthese'; use Regexp::Common 'whitespace'; my $f = ' this is a string with spaces to remove '; cmpthese(-3, { 'Regexp-Common' => sub { $_=$f; s/$RE{ws}{crop}//g; }, 'two-s///' => sub { $_=$f; s/^\s+//; s/\s+$//; }, 'one-s///' => sub { $_=$f; s/^\s+|\s+$//g; }, 's-capture' => sub { $_=$f; s/^\s*(.*?)\s*$/$1/; }, 's-capture2' => sub { $_=$f; s/^\s*(\S+(?:\s+\S+)?)?\s*$/$1/; }, 'm-capture' => sub { $_=$f; ($_) = /(\S+(?:\s+\S+)?)/; }, });
Rate Regexp-Common s-capture one-s/// s-capture2 m-ca +pture two-s/// Regexp-Common 659/s -- -91% -93% -95% + -96% -97% s-capture 7002/s 963% -- -21% -45% + -59% -73% one-s/// 8857/s 1244% 26% -- -30% + -48% -66% s-capture2 12699/s 1827% 81% 43% -- + -26% -51% m-capture 17179/s 2507% 145% 94% 35% + -- -34% two-s/// 25941/s 3837% 270% 193% 104% + 51% --
Not surprisingly, the straightforward method of calling s/// twice is the fastest. What is surprising is how slow Regexp-Common turns out to be, and I was pleasantly surprised at how well m-capture did. If, for some bizarre reason, you needed a single atomic expression to remove leading and trailing whitespace, that would seem to be the way to go.

In reply to Re: How do I remove whitespace at the beginning or end of my string? by Roy Johnson
in thread How do I remove whitespace at the beginning or end of my string? by vroom

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.