But the regex /\s+$/ is not anchored (and this grieves me). I've used this example time and time again when explaining regex reversal and that whole tangent, and it's useful again. If the regex were really anchored (that is, immovable), it would find the end of the string, and then match the regex in that context -- that is, the regex would have to terminate at the end of the string. As it stands, Perl can't optimize the regex that way, and we end up matching EVERY chunk of whitespace, and then testing to see if END-OF-STRING comes after it.

I think its important to remember this point only applies to \z (and maybe, I think, \Z) and where $ is the same as \z.

The logic makes sense when $ is actually end of line and not end of string, as it means doing a scan through the string to find the newline, which means it might as well keep track of state as it goes so it knows where the spaces start.

I guess what is a pity is that there isn't an optimization that handles this as a special case. It seems to me that patterns of this type could be special cased somehow. (And I mean this in the general case of /CLASS QUANTIFIER EOS/ and not just /\s+$/)

---
$world=~s/war/peace/g


In reply to Re: The "anchor" misnomer in regexes by demerphq
in thread The "anchor" misnomer in regexes by japhy

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.