Fellow monks,

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.


In reply to Recursing through hash of arrays by Popcorn Dave

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.