Perl 6是否有内置工具来制作嵌套数据结构的深层副本?
添加了示例:
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"
答案 0 :(得分:9)
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;
使用.clone
和.deepmap
请求数据结构的副本/深层副本。但不要赌它。任何对象都可以定义自己的.clone
方法,并用它做任何想做的事情。如果必须进行变异,因此必须进行克隆,请确保使用大型数据集测试程序。糟糕的算法会使程序在生产中几乎无用。
答案 1 :(得分:3)
肮脏的方式:
#!/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是危险的,应该避免使用。