Popcorn Dave has asked for the wisdom of the Perl Monks concerning the following question:
References are not my strongest point and so I'm trying to increase my knowledge about them. I'm stumped on why the following bit of code is misbehaving. I'm trying to recursively traverse the hash of arrays using the elements of the array in {start} as the keys to access the succesive elements.
#!/usr/bin/perl use strict; my %found = ( start => ["a", "b", "d", "g"], a => ["c","e"], b => [], c => ["f"], d => ["e"], e => [], f => [], g => [], ); print_tree('start', ''); sub print_tree{ my ($sub, $tab) = @_; foreach (@{$found{$sub}}){ print "$tab$found{$sub}[$_]\n"; $tab .= "\t"; print_tree($found{$sub}[$_], $tab); } }
The problem is that when I run it, I get the following output:
> Executing: C:\PROGRAM FILES\CONTEXT\ConExec.exe "c:\perl\bin\perl.ex +e" "subtest.pl" a c f c f a c f c f a c f c f a c f c f > Execution finished.
Where as I'm expecting:
a c f e b d e g
I did try to use a return outside my foreach loop but it still won't traverse the initial hash key's array. Can someone please shed some light on where I've gone wrong?
In addition, why isn't the $tab being pushed locally and returned? It seems that it keeps being added to, causing the spacing to go astray.
Thanks in advance!
There is no emoticon for what I'm feeling now.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Recursing through hash of arrays
by merlyn (Sage) on Jun 24, 2003 at 17:57 UTC | |
by Popcorn Dave (Abbot) on Jun 24, 2003 at 18:13 UTC | |
by merlyn (Sage) on Jun 24, 2003 at 18:16 UTC | |
|
Re: Recursing through hash of arrays
by LanceDeeply (Chaplain) on Jun 24, 2003 at 18:14 UTC |