punkish has asked for the wisdom of the Perl Monks concerning the following question:
my $in = [ {c_id => 1, r_to => 0, dept => 0, p_id => 1, comm => 'this',}, {c_id => 3, r_to => 1, dept => 1, p_id => 1, comm => 'the other',}, {c_id => 5, r_to => 1, dept => 1, p_id => 1, comm => 'else',}, {c_id => 6, r_to => 5, dept => 2, p_id => 1, comm => 'that',}, {c_id => 7, r_to => 6, dept => 3, p_id => 1, comm => 'moreover',}, {c_id => 9, r_to => 3, dept => 2, p_id => 1, comm => 'no way',}, {c_id => 10, r_to => 9, dept => 3, p_id => 1, comm => 'give',}, ];
I would create a sub foo, that would take as input a r_to, traverse the AoH, print out the line, then call itself with the c_id of that line. The result would be
1: this - 3: the other - 9: no way - 10: give - 5: else - 6: that - 7: moreover
I wrote a bunch of code, messed it up, and then went about looking for examples. I found the oh so wise BrowserUk's contribution in the node Re: Cleaner code to build hierarchical display of page names funnily called traverse! A little bit of editing, and I had the following working beautifully --
traverse($in,0,0, sub {print ' ' x $_->{dept},'-',$_->{comm},"\n";}); sub traverse { my( $ref, $reply_to, $depth, $code) = @_; for my $node ( grep{ ($_->{dept} == $depth) && ($_->{r_to} == $reply_to) } @$ref ) { local $_ = $node; $code->(); traverse($ref, $node->{c_id}, ($depth + 1), $code); } }
Then I started wondering why the anon sub was being passed as a param to the sub traverse. Not knowing why, I decided to remove it like so.
traverse($in, 0, 0); sub traverse { my( $ref, $reply_to, $depth) = @_; for ( grep{ ($_->{dept} == $depth) && ($_->{r_to} == $reply_to) } @$ref ) { print ' ' x $_->{dept}, '-', $_->{comm}, "\n"; traverse($ref, $_->{c_id}, ($depth + 1)); } }
And that too worked beautifully. So, I ask the following --
In anticipation...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Passing anon sub as param
by ikegami (Patriarch) on Jul 28, 2005 at 20:29 UTC | |
by punkish (Priest) on Jul 28, 2005 at 20:36 UTC | |
by fishbot_v2 (Chaplain) on Jul 28, 2005 at 20:54 UTC | |
by ikegami (Patriarch) on Jul 28, 2005 at 20:56 UTC | |
by GrandFather (Saint) on Jul 28, 2005 at 20:52 UTC | |
|
Re: Passing anon sub as param
by tmoertel (Chaplain) on Jul 28, 2005 at 22:21 UTC | |
|
Re: Passing anon sub as param
by polettix (Vicar) on Jul 28, 2005 at 23:27 UTC |