# build a hash with son => father as key => value pairs my %sons; while() { chomp; next unless $_; my ($son, $father) = split /\s+/, $_; $sons{$son} = $father; } # make another hash keyed on the fathers that includes all their sons my %fathers; for my $son ( keys %sons ) { # find the father or $son from out %sons hash my $father = $sons{$son}; push @{$fathers{$father}}, $son; } # show the results: print "Son\tFather\n"; for my $son ( keys %sons ) { print $son, "\t", $sons{$son}, "\n"; } print "\n\nFather\tSon(s)\n"; for my $father ( keys %fathers ) { my @sons = @{$fathers{$father}}; my $sons = join " | ", @sons; print $father, "\t\t", $sons, "\n"; } __DATA__ 1 1 2 2 3 3 4 1 5 3 6 4 7 5 8 1 9 2 #### Son Father 1 1 2 2 3 3 4 1 5 3 6 4 7 5 8 1 9 2 Father Son(s) 1 1 | 4 | 8 2 2 | 9 3 3 | 5 4 6 5 7