pelagic has asked for the wisdom of the Perl Monks concerning the following question:

Nuns and monks,
this is a well known feature: if you copy a hash-slice you actually copy references. Following a example snippet:
use strict; use Data::Dumper; my %original_hash = ( 'K1' => [ {'job' => '_DPL' ,'time' => '_MO_SU_2300' } ] ); my @slice_1 = map {{%$_}} @{$original_hash{'K1'}}; print "original_hash: ", Dumper \%original_hash; print "slice_1: ", Dumper \@slice_1; foreach my $item (@slice_1) { $item->{'job'} = 'fubar'; } print "slice_1 after manipulation: ", Dumper \@slice_1; print "original_hash after manipulation within slice_1: ", Dumper \%or +iginal_hash; my @slice_2 = @{ $original_hash{'K1'} }; foreach my $item (@slice_2) { $item->{'job'} = 'fubar'; } print "slice_2 after manipulation: ", Dumper \@slice_2; print "original_hash after manipulation within slice_2: ", Dumper \%or +iginal_hash; ___OUTPUT___ original_hash: $VAR1 = { 'K1' => [ { 'time' => '_MO_SU_2300', 'job' => '_DPL' } ] }; slice_1: $VAR1 = [ { 'time' => '_MO_SU_2300', 'job' => '_DPL' } ]; slice_1 after manipulation: $VAR1 = [ { 'time' => '_MO_SU_2300', 'job' => 'fubar' } ]; original_hash after manipulation within slice_1: $VAR1 = { 'K1' => [ { 'time' => '_MO_SU_2300', 'job' => '_DPL' } ] }; slice_2 after manipulation: $VAR1 = [ { 'time' => '_MO_SU_2300', 'job' => 'fubar' } ]; original_hash after manipulation within slice_2: $VAR1 = { 'K1' => [ { 'time' => '_MO_SU_2300', 'job' => 'fubar' } ] };
Copying into @slice_1 I use map to create new anonymous data. So the problem is solved: I can change the copy without changing the original also.
But is there a better solution to do that? Some sort of "deep copy"?

pelagic

Replies are listed 'Best First'.
Re: "Physical" copy of structured data.
by japhy (Canon) on Aug 12, 2004 at 15:36 UTC
    I believe Storable has a dclone() function.

    Update: see also Clone.

    _____________________________________________________
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: "Physical" copy of structured data.
by Tomte (Priest) on Aug 12, 2004 at 15:36 UTC

    I guess you'll find merlyns column Deep copying, not Deep secrets an interesting read on the subject.

    regards,
    tomte


    An intellectual is someone whose mind watches itself.
    -- Albert Camus

      Thanks a lot japhy & Tomte!
      Both hints very interesting and helpful.

      pelagic