Here's an efficient method:
use strict; use warnings; my %groupOfBact = ( group1 => { strain1 => 1, strain2 => 1, strain4 => 1, }, group2 => { strain3 => 1, strain4 => 1, strain5 => 1, }, group3 => { strain6 => 1, strain7 => 1, }, ); my %bact_by_strain; for my $bact ( sort keys %groupOfBact ) { for my $strain ( keys %{ $groupOfBact{$bact} } ) { push @{ $bact_by_strain{$strain} }, $bact; } } my %delete; for my $strain ( keys %bact_by_strain ) { my $bacts = $bact_by_strain{$strain}; next if @$bacts < 2; my $dst = $bacts->[0]; for my $src ( @{$bacts}[ 1..$#$bacts ] ) { my $src_bact = $groupOfBact{$src}; my $dst_bact = $groupOfBact{$dst}; next if $src_bact == $dst_bact; %$dst_bact = ( %$dst_bact, %$src_bact ); $groupOfBact{$src} = $groupOfBact{$dst}; $delete{$src} = 1; } } delete @groupOfBact{ keys %delete }; use Data::Dumper qw( Dumper ); print(Dumper(\%groupOfBact));

It still does some unnecessary merges, though. ( Actually no, I fixed that before posting )

Update: This is the approach moritz mentioned.


In reply to Re: Merging Complex Hashes by ikegami
in thread Merging Complex Hashes by jpearl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.