Copying a hashref in Perl [duplicate]

When you copy a hashref into another scalar, you are copying a reference to the same hash. This is similar to copying one pointer into another, but not changing any of the pointed-to memory.

You can create a shallow copy of a hash easily:

my $copy = { %$source };

The %$source bit in list context will expand to the list of key value pairs. The curly braces (the anonymous hash constructor) then takes that list an creates a new hashref out of it. A shallow copy is fine if your structure is 1-dimensional, or if you do not need to clone any of the contained data structures.

To do a full deep copy, you can use the core module Storable.

use Storable 'dclone';

my $deep_copy = dclone $source;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)