I have two display subroutines; one gives all the unique descendants of a concept, and the other prints an indented tree-structure of the whole 'terminology'. Each of them recursively pops the elements off of a hash of "immediate children" that was constructed with a split of the original table data.
My problem: Either subroutine on its own works fine, but both together do not. Only one display (either the tree or the unique list) works, and the other shows only one element. I tried building the hash anew after each of these subroutine calls, (as the program shows) but that did not help.
I enclose the code with one of the routines commented out. Entering "taxonomy" at the prompt will display the whole tree. Thanks for any help.
John
#gives all descendents for a tree, given a root node use strict; use warnings; my ($curr_string, $in, $select, %immed_child, %all_descends); process_input(); load_hashes(); #make_display_string("$in"); #print "\n$curr_string\n"; load_hashes(); show_results(); sub process_input{ while(1){ print qq(enter concept name or "Q" to quit\n); chomp($in = <>); exit() if $in =~ /^\s*q\s*$/i; $in =~s/^\s*(\w+)\s*$/$1/; # still need to check if a valid concept print qq(enter:\n"A" for all descendents,\n"I" for immediate c +hildren\n"P" for parents\n); chomp($select = <>); $select =~ s/^\s*([aip])\s*$/$1/i; last; } } # key: parent # val: list of immediate children sub load_hashes{ my ($child, $par); while(<DATA>){ chomp; ($child, $par) = split/\t/; push @{$immed_child{$par}}, $child; } } #global hash needed to exchange vals w other subs sub get_descends{ my $root = shift; $all_descends{$root}++ if $root; while(1){ last unless my $immed = pop @{$immed_child{$root}}; get_descends($immed); $all_descends{$immed}++; } return keys %all_descends; } sub make_display_string{ my $root = shift; my $level = shift ; $curr_string = shift || $root; # $curr_string = "\n". $curr_string; $level++; while (1){ last unless my $immed = pop @{$immed_child{$root}}; $curr_string .="\n". "\t" x $level . $immed; make_display_string($immed, $level, $curr_string); } #$curr_string = "\n" . $curr_string; } sub show_results{ $" = "\n\t"; if ($select =~ m/a/i){ print qq(\ndescendents of \n"$in":\n); my @descends = get_descends($in); print "\t@descends\n"; } elsif ($select =~m/i/i){ if (@{$immed_child{$in}}){ print qq(\nimmediate children of \n"$in":\n); print "\t@{$immed_child{$in}}\n"; } else{ print "no immediate children of $in"; } } elsif ($select =~ m/p/i){ print "working on this\n"; } } __DATA__ vehicle taxonomy exercise device taxonomy computer topic taxonomy automobile vehicle ford automobile chevy automobile bike vehicles bike exercise device jumprope exercise device treadmill exercise device perl computer topic database computer topic
In reply to recursive difficulty by jjohhn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |