user
Task

Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.

The task should show:

* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.

* Any limitations of the method.

* That the structure and its copy are different.

* Suitable links to external documentation for common libraries.
assistant
(formerly Perl 6)

Raku doesn't currently provide a proper mechanism for deep copies, but depending on your requirements you could use one of these work-arounds:

**1) Use `.deepmap(*.clone)`:**

.deepmap constructs a copy of the data structure, and .clone makes a shallow copy of each leaf node. Limitations:

* Hangs indefinitely when given a self-referential data structure.
* Descends only into Iterable collections (like Array/Hash), which means that a Pair or a typical custom object would be considered a leaf node.

```
my %x = foo => 0, bar => [0, 1];
my %y = %x.deepmap(*.clone);

%x<bar>[1]++;
say %x;
say %y;

```

Output:

```
{bar => [0 2], foo => 0}
{bar => [0 1], foo => 0}

```

**2) Use `.raku.EVAL`:**

.raku serializes the data structure to Raku code, and .EVAL deserializes it. Limitations:

* Doesn't work correctly if the data structure contains elements that can't be properly serialized, such as closures or file handles.

```
my %x = foo => 0, bar => [0, 1];
my %y = %x.raku.EVAL;

%x<bar>[1]++;
say %x;
say %y;

```

Output:

```
{bar => [0 2], foo => 0}
{bar => [0 1], foo => 0}

```