my %hNewGroups; oldgroup: foreach my $sGroup (keys %hGroups) { my $hGroupMembers = $hGroups{$sGroup}; # check each new group for genes in common with # current old group ($sGroup) foreach my $sNewGroup (keys %hNewGroups) { # check genes in the old group to see if any are # in the new group ($sNewGroup). # Note: use exists to prevent auto-vivification # (automatic adding) of $sGene to the members hash my $hNewGroupMembers = $hNewGroups{$sNewGroup}; foreach my $sGene (keys %$hGroupMembers) { if (exists($hNewGroupMembers->{$sGene})) { $hNewGroups{$sNewGroup} = { %$hNewGroupMembers , %$hGroupMembers }; next oldgroup; } } } # create a new group, since no gene is in common with # other groups found so far $hNewGroups{$sGroup} = $hGroupMembers; }