Does Perl 6 have a built-in tool for creating a deep copy of a nested data structure?

Does Perl 6 have a built-in tool for creating a deep copy of a nested data structure?

Added example:

my %hash_A = (
    a => {
        aa => [ 1, 2, 3, 4, 5 ],
        bb => { aaa => 1, bbb => 2 },
    },
);


my %hash_B = %hash_A;
#my %hash_B = %hash_A.clone; # same result

%hash_B<a><aa>[2] = 735;

say %hash_A<a><aa>[2]; # says "735" but would like get "3"
+4
source share
2 answers
my %A = (
    a => {
        aa => [ 1, 2, 3, 4, 5 ],
        bb => { aaa => 1, bbb => 2 },
    },
);

my %B = %A.deepmap(-> $c is copy {$c}); # make sure we get a new container instead of cloning the value

dd %A;
dd %B;

%B<a><aa>[2] = 735;

dd %A;
dd %B;

Use .cloneand deepmapto request a copy / deep copy of the data structure. But do not bet on it. Any object can determine it by the method cloneand do whatever it wants with it. If you must mutate and therefore must clone, make sure you test your program with large data sets. Bad algorithms can make a program almost useless in production.

+5
source

:

#!/usr/local/bin/perl6

use v6;
use MONKEY-SEE-NO-EVAL;

my %hash_A = (
    a => {
        aa => [ 1, 2, 3, 4, 5 ],
        bb => { aaa => 1, bbb => 2 },
    },
);


my %hash_B;
EVAL '%hash_B = (' ~ %hash_A.perl ~ ' )';

%hash_B<a><aa>[2] = 735;

say %hash_A;
say %hash_B;

:

$ perl6 test.p6
{a => {aa => [1 2 3 4 5], bb => {aaa => 1, bbb => 2}}}
{a => {aa => [1 2 735 4 5], bb => {aaa => 1, bbb => 2}}}

, , . EVAL .

+2

Source: https://habr.com/ru/post/1649119/


All Articles