Last active
May 6, 2019 15:51
-
-
Save kevincolyer/7aad41a836beb1eb75cd to your computer and use it in GitHub Desktop.
Perl6 object cloning test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl6 | |
use v6; | |
class obj { | |
has $.attr is rw = 42; | |
has @.shallow = 1,2,3; | |
has @.deep = [1,2,3],[4,5,6]; | |
} | |
my $a = obj.new; | |
my $b = $a.clone; | |
my $c = $a; | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
$a.deep[1][0]="a"; | |
$a.shallow[0]="a"; | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
$b.deep[1][1]="b"; # changes a | |
$b.shallow[1]="b"; # changes a | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
$c.deep[1][2]="c"; # changes a | |
$c.shallow[2]="c"; # changes a | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
$c.attr=44; # changes a | |
$b.attr=43; # changes ONLY b | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
copying($a); | |
immutable($a); | |
sub copying (obj $d is copy) { | |
$d.attr=0; | |
$d.shallow[0]='d'; | |
$d.deep[1][0]='d'; | |
say "in sub copying"; | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
say $d.perl; | |
} | |
sub immutable (obj $e) { | |
use Test; | |
$e.attr=1; | |
$e.shallow[0]='e'; | |
$e.deep[1][0]='e'; | |
say "in sub immutable"; | |
say $a.perl; | |
say $b.perl; | |
say $c.perl; | |
say $e.perl; | |
} | |
say "cloning using .clone and passing attribs in"; | |
my $f = $a.clone(deep => ( [7,8,9],[10,11,12] ) ); | |
say "f: " ~ $f.perl; | |
$f.deep[0][0]=1001; | |
say "a: " ~ $a.perl; | |
say "f: " ~ $f.perl; | |
say "cloning using .clone and attrs from a"; | |
my $g = $f.clone(deep => $a.deep ); | |
say "g: " ~ $g.perl; | |
$g.deep[0][0]=42; | |
say "g: " ~ $g.perl; | |
say "a: " ~ $a.perl; | |
say "f: " ~ $f.perl; | |
say "cloning using .clone and attrs from a"; | |
my $h = $f.clone(deep => $a.deep.clone ); | |
say "h: " ~ $h.perl; | |
$h.deep[0][0]=43; | |
say "h: " ~ $h.perl; | |
say "a: " ~ $a.perl; | |
say "f: " ~ $f.perl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment