yes, it is broken. the reason is that the pattern is only matching the leading space and nothing else -- ie:

$_ = ' blee blah '; s/\s*(.*?)\s*/$1/; print "matched '$&'; retained '$1'; str is '$_'\n";
which gives matched '       '; retained ''; str is 'blee blah    '

to strip whitespace, the minimal match needs to be forcibly anchored to match to the end of the string, ie:  s/^\s*(.+?)\s*$/$1/, which now successfully strips leading & training whitespace.

however this is a poor way to do it. it is clearer and faster to use 2 regexps, one to strip leading \s, the other the trailing \s; ie:

s/^\s+//; s/\s+$//;

using 2 regexps is also quite a bit faster than the single regexp too:

[matt@blade8 matt]$ perl -MBenchmark -e '@list1 = @list2 = map { " "x +rand(100) . "some text" . " "x rand(100) } 1 .. 100; timethese( 100_ +000, { single_regexp => sub { return map { s/^\s*(.+?)\s*$/$1/; $_ } + @list1 }, dual_regexp => sub { return map { s/^\s+//; s/\s+$//; $_ } + @list2 } } ); ' Benchmark: timing 100000 iterations of single_regexp, dual_regexp... single_regexp: 56 wallclock secs (56.04 usr + 0.00 sys = 56.04 CPU +) @ 1784.44/s (n=100000) dual_regexp: 17 wallclock secs (18.63 usr + 0.00 sys = 18.63 CPU) +@ 5367.69/s (n=100000)


In reply to Re: Weird Regex in CGI::Cookie by d_i_r_t_y
in thread Weird Regex in CGI::Cookie by enoch

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.