why do the regexes /^a$/ and /^a$\n/ match "a\n\n" in only the multi-line mode (they match "a\n" in all three modes)?

I think the key here is that, absent /m: $ matches end-of-string or just before a newline at end-of-string. So, /^a$/ matches "a" and "a\n", but not "a\n\n" or "a\nq" -- the latter two because there is something after the "\n" that the $ matches at.

Now: /^a$\n/ is a bit odd. It matches "a\n", which I think we can read as: (a) the $ successfully matching in front of the \n, and then the \n matching the \n. It does not match "a" -- because while the $ matches, the \n does not. It also does not match "a\n\n" -- because the $ does not match. [m/.+$\n/ can be read as requiring a not-empty string terminated by exactly one \n.]

Looking at /^a$/m, now $ will match end-of-string or just before a newline anywhere in the string. So now it matches "a\n\n" because $ matches before the first \n (under /m it doesn't matter that it's not at end of string), then the \n matches the first \n in the string.

And /^a$\n/m, matches "a\n\n" because $ matches before the first \n, then the \n matches the first \n in the string.

In passing, I note that Perl accepts m'^a$q' which can never match... unless /m is somehow implied (eg Regexp::Autoflags ?) Perhaps it's just too hard to spot the degenerate case ?

Update: with thanks to AnomalousMonk for pointing out my soggy thinking, below -- of course, when $ matches a \n it matches before it. So only m/$\n/ can hope to match ! (I knew that, dammit.)


In reply to Re: When exactly do Perl regex's require a full match on a string? by gone2015
in thread When exactly do Perl regex's require a full match on a string? by ELISHEVA

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.