paulzakas has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to organize a flat file into an org-chart type hierarchy.

The flat file contains many rows that each contain an employee name and their direct manager's name.

So far I've successfully read through the file line by line and loaded the hash of arrays with the following line:

push(@{$hash{$manager}}, $employee);

Now I want to start with the top employee (CEO) and print a hierarchical output like this, all the way to the lowest level:

CEO
  VP1
    DIRECTOR1
    DIRECTOR2
        EMPLOYEE1
  VP2
    DIRECTOR3
    DIRECTOR4
        EMPLOYEE2

I can print the first level, of course, but I'm not sure how to go about extending this to walk through the whole structure:

for $i ( 0 .. $#{ $hash{"CEO"} } ) { print $hash{"CEO"}[$i] . "\n"; }

Would appreciate some guidance, thanks!

Replies are listed 'Best First'.
Re: Recursive walk through hash of arrays
by choroba (Cardinal) on Feb 10, 2012 at 15:47 UTC
    The answer is already present in the title of the question: recursion. Use it.
    sub walk { my ($person, $level) = @_; say " " x $level, $person; for my $lower (@{ $hash{$person} }) { walk($lower, $level+1) } } walk("CEO",0);
Re: Recursive walk through hash of arrays
by Anonymous Monk on Feb 11, 2012 at 03:48 UTC
    "walk" has an easy recursive definition. If "ref($here) eq 'HASH')" then call yourself recursively with an increased level-of-nesting; otherwise, print the current element out at the current nesting level and return.