Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Action at a distance

by ikegami (Patriarch)
on Nov 03, 2022 at 14:41 UTC ( [id://11147948]=note: print w/replies, xml ) Need Help??


in reply to Action at a distance

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?

Replies are listed 'Best First'.
Re^2: Action at a distance
by karlgoethebier (Abbot) on Nov 03, 2022 at 19:26 UTC
    "To avoid getting bit by this…"

    BTW, what prevents me from doing something like this?

    package Acme; use parent 'Clone'; …

    And later:

    my $object = Acme->new; my $copy = $object->clone;

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

      > BTW, what prevents me from doing something like this?

      Nothing.

      You can always do it explicitly, as long as a ->clone method is available.

      But the OP wants this to happen implicitly, when he does my $copy = $magic_object;

      Cheers Rolf
      (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
      Wikisyntax for the Monastery

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11147948]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-03-28 16:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found