#!/usr/bin/perl use warnings; use strict; my %adjacent; while () { my @component = split /\,/, $_, 3; my $parent; if ( defined($adjacent{$component[0]})) { $adjacent{$component[0]}{$component[1]} = $component[2]; } elsif ( defined($adjacent{$component[1]})) { $adjacent{$component[1]}{$component[0]} = $component[2]; } elsif ( $parent = has_parent($component[0]) ) { $adjacent{$parent}{$component[1]} = $component[2]; } elsif ( $parent = has_parent($component[1]) ) { $adjacent{$parent}{$component[0]} = $component[2]; } else { $adjacent{$component[0]}{$component[1]} = $component[2]; } } print "\n\n*----------------------------------------------*\n"; for my $inner ( sort keys %adjacent ) { print "$inner "; for my $outer ( sort keys %{$adjacent{$inner}} ) { print ", $outer"; } print "\n"; } sub has_parent { my $candidate = shift; for my $inner ( sort keys %adjacent ) { for my $outer ( sort keys %{$adjacent{$inner}} ) { if ( $candidate eq $outer ) { return $inner; } } } return 0; } __DATA__ Gene1,Gene2,spc1,spc2 Gene3,Gene1,spc1,spc2,spc4 Gene4,Gene1,spc1,spc2,spc5,spc3,spc1 Gene2,Gene3,spc1,spc2 Gene2,Gene4,spc2,spc3 Gene3,Gene4,spc1,spc2 GeneA,GeneB,spc4,spc5 GeneB,GeneC,spc1,spc2 GeneC,GeneD,spc1,spc2 GeneD,GeneE,spc4,spc2 GeneE,GeneF,spc3,spc1 GeneX,GeneY,spc6,spc8 GeneX,GeneP,spc6,spc7