use strict; my %hash; while (){ chomp; my @array = split(',',$_); my ($child, $parent) = ($2,$1); $hash{$array[1]} = [] unless (exists $hash{$array[1]}); push @{$hash{$array[1]}}, $array[0]; } #and now you do the Johnny Cash (walk the line) my @line; _Johnny(5); # entry that you wish to query foreach (@line){ print $_ . ","; } #------------------------------------------------# sub _Johnny { my $x = shift; push (@line,$x); for (@{$hash{$x}}){ _Johnny($_); } } #------------------------------------------------# __DATA__ 3,1 5,1 4,3 2,7 6,4 8,2 7,6 11,5 12,5 43,11 15,11