Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: deep copy, not deep create

by eclark (Scribe)
on May 25, 2004 at 21:50 UTC ( #356395=note: print w/replies, xml ) Need Help??


in reply to deep copy, not deep create

I agree with saintmike. What you want to do is better using OO. To use the approach you are now, you can do something like this. See my deepmerge function. It is not complete, but works for your sample data. To complete it you need to handle all data types.

#!/usr/bin/perl use strict; use Data::Dumper; my %europe = ( skin => "euro-white", language => { default => "euro-englisch", instrument => "euro-clarinet", }, politics => "euro-democratic", ); my %german = ( skin => "de-white", language => { default => "de-german" } ); my %bavarian = ( skin => "bav-white", language => { default => "bav-bavarian" } ); # this is not enough, german/language overwrites # the complete hash of euro/language my %woman = %europe; deepmerge(\%woman, \%german); deepmerge(\%woman, \%bavarian); print Dumper(\%woman); # result is this: # $VAR1 = { # 'skin' => 'bav-white', # 'politics' => 'euro-democratic', # 'language' => { # 'default' => 'bav-bavarian' # ** this is not here: instrument => "euro-clarinet", # } # }; unless ($woman{language}->{instrument}) { die "Error: Language instrument is not there"; } else { print "It worked\n"; } sub deepmerge { my ($into, $this) = @_; for my $k (keys %$this) { if (defined $k and exists $into->{$k} and defined $into->{$k} and ref($into->{$k}) eq 'HASH' and ref($this->{$k}) eq 'HASH') { deepmerge($into->{$k}, $this->{$k}); } elsif (defined $k) { $into->{$k} = $this->{$k}; } } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://356395]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2021-12-09 05:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (36 votes). Check out past polls.

    Notices?