For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > December 2004 > RE : Copying a hash-of-hashes









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author RE : Copying a hash-of-hashes
Jose Nyimi

2004-12-30, 3:56 pm



> -----Message d'origine-----
> De=A0: Peter Rabbitson [mailto:rabbit@rabbit.us]
> Envoy=E9=A0: jeudi 30 d=E9cembre 2004 04:58
> =C0=A0: beginners@perl.org
> Objet=A0: Copying a hash-of-hashes
>=20
> Hello List,
> To explain the problem I am having, I wrote a simple snipet that

doesn't
> do
> anything meaningful other than illustrating the behaviour I want to

avoid:
>=20
> my %hoh =3D (
> 1 =3D> {
> a =3D> 5, b =3D> 5
> },
>=20
> 2 =3D> 5
> );
>=20
>=20
> my @res =3D &RANDOMSUB; #call a random subroutine
>=20
> print "$hoh{1}{a} $hoh{2} \n";
>=20
>=20
> sub RANDOMSUB {
> my %hohcopy =3D %hoh;
>=20
> $hohcopy{1}{a} =3D 2;
> $hohcopy{2} =3D 2;
> }
>=20
local[color=darkred]
> hash
> %hohcopy all the values assigned to it have no meaning in the main

body.
> However the print produces 2, 5 instead of the desired 5, 5. As far as

my
> understanding goes this is due to the fact that $hohcopy{1} holds a
> reference to $hoh{1} instead of recreating it's internal structure
> entirely
> from the root to the leaves while performing a copy.
>=20
> The question is whether there is an elegant way to produce a complete

copy
> of a hash-of-hashes-of-hashes-...-of-hashes for internal subroutine
> purposes
> and make sure that all references will be translated properly as well,
> leaving the subroutine no ability to modify the main hash.
>=20
> Thank you.
>=20


Hello,

This is well known behavior.
Try google on "deep copy" ...

On elegant way I know to do a "deep copy" in Perl
is to use dclone method of Storable module.

Something =E0 la:

use Storable qw(dclone);
my $hohcopy_ref =3D dclone \%hoh;

HTH,

Jos=E9.


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com