use strict; use warnings; sub ancestors { my $node_parents = shift; my $node = shift; my @ancestors; while (defined($node_parents->{$node})) { push @ancestors,$node_parents->{$node}; $node=$node_parents->{$node}; } return wantarray ? @ancestors : \@ancestors } my %node_parent; #my $data_file="reff.data"; #open my $dat_fh, $data_file or die "Could not open $data_file: $!"); #while (<$dat_fh>) { while () { if (/^\s*(\d+)\s+(\d+)/) { $node_parent{$1}=$2; } } my $check_node='6'; print "Ancestory of $check_node from newest to oldest:\n"; print join(", ",ancestors(\%node_parent,$check_node)); # the tree looks like: # 0 # +-+-+ # 1 2 # +-+ +++ # 3 4 5 # +-+-+ # 6 7 8 # # so we should get the output: # Ancestory of 6 from newest to oldest: # 3, 1, 0 __DATA__ 1 0 2 0 3 1 4 2 5 2 6 3 7 3 8 3