[kw-pm] Hash Question
Matt Sergeant
matt at sergeant.org
Tue Mar 1 11:00:59 PST 2011
Robert Pike wrote:
> I have a complex hash that I want to make a "copy" of before manipulating the original hash.
> Here is what I have :
> my %tmpData = %{$aDATA};
> If I make changes to %{%aDATA} the changes are reflected in %tmpData. How can I copy the hash without having to loop through each element and assigning to the backup copy? Thanks.
>
The perl FAQ is your friend:
$ perldoc -q copy
Found in /usr/share/perl/5.8/pod/perlfaq4.pod
How do I print out or copy a recursive data structure?
The Data::Dumper module on CPAN (or the 5.005 release of Perl)
is great
for printing out data structures. The Storable module on CPAN
(or the
5.8 release of Perl), provides a function called "dclone" that
recur-
sively copies its argument.
use Storable qw(dclone);
$r2 = dclone($r1);
Where $r1 can be a reference to any kind of data structure you'd
like.
It will be deeply copied. Because "dclone" takes and returns refer-
ences, you'd have to add extra punctuation if you had a hash of
arrays
that you wanted to copy.
%newhash = %{ dclone(\%oldhash) };
More information about the kw-pm
mailing list