I think I've struck it before ... something to do with the wonderful Copy-On-Write, IIRC.

Quite the opposite. If anything, it's about the lack of copy on write.

$x and $y are references to objects. You are copying the reference, but not the referenced object (on write or otherwise).

You want $y = $x->copy(); to create a clone.

Is there some way (apart from building perl without COW) to guard against getting bitten by this ?

To avoid getting bit by this, only uses classes that provide immutable objects.

Also, you'll need to avoid references to arrays and hashes, as the same issue is found there.

my $x = [ 4 ]; my $y = $x ++$_ for @x; say @y; # 5!!

Even then, you'll have to worry about aliases.

Is it a bug in perl ?

It's a performance concession. Using immutable objects has a high cost.

You brought up Perl's COW mechanism for strings. It's specifically a mechanism to mitigate these costs. For strings. Imagine having to build COW into all your classes... And how it would work for classes that reference external (to perl) resources?


In reply to Re: Action at a distance by ikegami
in thread Action at a distance by syphilis

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.