This is apparently a bug/limitation related to the copy-on-write (COW) mechanism.


In the first snippet, $A and the constant initially share the same string buffer. Once $A is modified, the COW mechanism comes into play making an unshared copy of the string buffer for $A. Something goes wrong at this point.

The workaround causes $A to have an unshared buffer going in.

Note that simply appending to a string can cause the string's buffer to be replaced with another larger one. This apparently doesn't trigger the bug. If you use Devel::Peek's Dump on the scalar before and after the m//, you'll see the address of the string buffer (PV) has changed. Even when the workaround is in play. So it seems to be a problem specific to the COW mechanism (added to Perl in version 5.20).


Finally, you shouldn't be surprised to have problems when modifying a variable on which an operation is being performed. for (@a) { say; pop(@a); } will give "interesting" results too, for example.


In reply to Re: Strange behaviour when regex variable is modified during match? by ikegami
in thread Strange behaviour when regex variable is modified during match? by rsFalse

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.