Logic error in the recursive function. Basically to make a recursive function, you either need to have a gradually reducing data set, or set a terminating condition, or both. I have wrote a small example below that prints an organization tree recursively. Note the terminating condition and reduced data set in the demo.

use strict; use warnings; my %employees = ( '1' => { boss_id => '1', emp_name => 'big boss', }, '2' => { boss_id => '1', emp_name => 'middle boss', }, '3' => { boss_id => '2', emp_name => 'worker 1', }, '4' => { boss_id => '1', emp_name => 'small boss', }, '5' => { boss_id => '2', emp_name => 'worker 2', }, '6' => { boss_id => '4', emp_name => 'worker 3', }, ); getreports(1); sub getreports { my ($id, $level) = @_; $level = $level || 0; die "Employee $id doesn't exist" if ! exists $employees{$id}; print ' ' x ($level * 3), "|\n", ' ' x ($level * 3), "+- $employees{$id}{emp_name}\n"; my @employees = (); foreach my $emp_id (keys %employees) { # find the employees under $id except # when boss is himself push @employees, $emp_id if $employees{$emp_id}{boss_id} eq $id && $emp_id ne $id; } return if $#employees < 0; getreports($_, $level + 1) foreach (@employees); }
And the output is -
| +- big boss | +- small boss | +- worker 3 | +- middle boss | +- worker 1 | +- worker 2

In reply to Re: Iterating over a hash, recursively, forever! by Roger
in thread Iterating over a hash, recursively, forever! by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.