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

Hi,
  The answer to this might be simple but I've been working late again, n can't seem to remember how to do it or find it on google.

I've got some sub routines that are returning a reference that contains a hash, that contains a few hashes, etc.

I want to run 2 or more of these routines and have the output put into one refence.

I.e.
Sub1 returns data
$hash->{key}->{data1} = v1;
$hash->{key}->{data2} = v2;
Sub2 returns data
$hash->{key}->{data3} = v3;
$hash->{key2}->{data1} = v1;

I want to end up with a scalar that has:-
$hash->{key}->{data1} = v1;
$hash->{key}->{data2} = v2;
$hash->{key}->{data3} = v3;
$hash->{key2}->{data1} = v1;

I'm sure it's simple, my brain just aint working.


Lyle

Replies are listed 'Best First'.
Re: Merging references
by ikegami (Patriarch) on Dec 28, 2006 at 07:04 UTC
    my $dst = Sub1(); my $src = Sub2(); foreach my $key1 (keys %$src) { my $inner = $src->{$key1}; foreach my $key2 (keys %$inner) { my $val = $inner->{$key2}; $dst->{$key1}{$key2} = $val; } }
      Or you could use a slice instead of the inner loop. The following piece is a rewrite, that is easily extended to more than merging the result of two subs:
      my $part1 = Sub1(); my $part2 = Sub2(); my $ans = {}; # where the final answer will live foreach my $part ($part1, $part2) { # loop over parts foreach my $k (keys %$part) { my $inner = $part->{$k}; @{$ans->{$k}}{keys %$inner} = values %$inner; } } use Data::Dump qw(dump); print dump $ans; # that's what you got

      Obviously, this merge only works at two-level hashes.

Re: Merging references
by ashokpj (Hermit) on Dec 28, 2006 at 13:49 UTC

    Hi,

    I use simple hash merge concept here. i think this code will help you

    use Data::Dumper; my $sub1 = { 'a' => {'apple' => 1 ,'ape' => 2}, 'b' => {'ball' => 1, 'bell' => 2} }; my $sub2 = { 'd' => {'dog' => 1}, 'c' => {'cat' => 1, 'clear'=> 2} }; my %hash = (%$sub1 ,%$sub2); print "\n". Dumper( \%hash);

    thanks

    ASHOK

      Unfortunately, that overwrites second-level hashes. Hash::Merge is a better solution.