in reply to Tree Analysis
You have a two nested for loops and so they can only print two levels. The easiest way is to use recursion. The following code has two solutions. get_all_chains will return an array of all of the call chains. print_all_chains will print the call chains as they are found.
which results in#!/usr/bin/perl -w use warnings; use strict; my ($tag, %list); while (<DATA>){ next unless /./; if (/^(\w+)/){ $tag = $1; next; } if (/^-- (\w+)/){ push @{$list{$tag}}, $1; } } print "get_call_chains\n"; print "---------------\n"; for my $call_chain ( get_call_chains("main") ){ print join(" ", @$call_chain),"\n"; } print "\n\n"; print "print_call_chains\n"; print "-----------------\n"; print_call_chains("main"); sub get_call_chains { my $root = shift; my @calls; if( exists $list{$root} ){ for (@{$list{$root}}){ push @calls, get_call_chains($_); } } else { @calls = ([]); } unshift @$_, $root for @calls; return @calls } sub print_call_chains { my @stack = @_; my $current = $stack[$#stack]; if(exists $list{$current}) { for (@{$list{$current}}){ print_call_chains(@stack, $_); } } else { print join(" ", @stack),"\n"; } } __END__ main -- check -- check1 check -- computing -- net check1 -- computing2 -- net2 computing -- community
get_call_chains --------------- main check computing community main check net main check1 computing2 main check1 net2 print_call_chains ----------------- main check computing community main check net main check1 computing2 main check1 net2
get_call_chains can be optimized by storing the result on the first call for a given subroutine, and using the stored value if it is ever called again with the same subroutine.
Note this version does not address the infinite loop if the analyzed code uses recursion.
|
|---|