my %animals; my @zoos; foreach my $state (keys %bighash) { foreach my $zoo (keys %{$bighash{$state}}) { foreach my $state2 (keys %bighash) { foreach my $zoo2 (keys %{$bighash{$state2}}) { my $animal1 = $bighash{$state}{$zoo}[1]; my $animal2 = $bighash{$state2}{$zoo2}[1]; if ( is_variation($animal1,$animal2) == 1 ) { #print "$animal1 - $animal2\n"; push @zoos, $zoo; } push @{$animals{$animal1}{$state}}, [@zoos]; } } } } print Dumper \%animals ; sub is_variation { #Test if two animals are variation of others: #e.g. HIPPO1 - HIPPO2 -> True # HIPPO1 - MONKEY2 -> False my ($s1,$s2) = @_; my ($t1,$t2); $s1 =~ /([A-Za-z]+)(\d+)$/; $t1 = $1; $s2 =~ /([A-Za-z]+)(\d+)$/; $t2 = $1; #print "$t1-$t2\n"; if ( $t1 eq $t2 ) { return 1; } return 0; }