In Perl, to perform a deep copy of nested structures (such as array hashes, hash arrays), you cannot use simple assignment or standard functions (@b = @a, %b = %a, $clone = $orig). Such operations create only a shallow copy: nested objects still reference the same memory locations.
For deep copying, you use:
Storable module:use Storable 'dclone'; my $deep_copy = dclone($structure);
Clone module: similar usage.It's important to remember: all levels of nesting are copied, including references within the structure.
What happens with simple assignment of a complex data structure: are nested elements copied?
Answer: No, only the top level is copied. Internal arrays and hashes remain shared between the original and the copy.
my $orig = { a => [1,2,3], b => { x => 7 } }; my $copy = $orig; $copy->{a}[0] = 99; # $orig->{a}[0] — will also become 99!
Only using deep cloning will give a fully independent copy.
Story 1
In a REST API application, requests for different clients were cloned through simple assignment of references. As a result, changes in one client's response instantly reflected for all others — because they all worked with the same nested data structure.
Story 2
When aggregating data from a complex array structure, copying was done through push (push @new, @old), forgetting about nested levels. A random change in the inner hash corrupted the data for all aggregates — the bug was hard to detect for a long time.
Story 3
For processing logs, the structure was duplicated through Clone, but special "magical" fields of objects were not taken into account — consequently, necessary methods/attributes were lost. As a result, the functionality was invalid, and the error only reproduced in production.