> -----Message d'origine----- > De : Peter Rabbitson [mailto:[EMAIL PROTECTED] > Envoyé : jeudi 30 décembre 2004 04:58 > À : beginners@perl.org > Objet : Copying a hash-of-hashes > > 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: > > my %hoh = ( > 1 => { > a => 5, b => 5 > }, > > 2 => 5 > ); > > > my @res = &RANDOMSUB; #call a random subroutine > > print "$hoh{1}{a} $hoh{2} \n"; > > > sub RANDOMSUB { > my %hohcopy = %hoh; > > $hohcopy{1}{a} = 2; > $hohcopy{2} = 2; > } > > >From my understanding since in the subroutine I am working with a local > 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. > > 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. > > Thank you. >
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 à la: use Storable qw(dclone); my $hohcopy_ref = dclone \%hoh; HTH, José. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>