I'm having one of those days...

I'm trying to build a hierarchical hash that reflects a string syntax that represents parent-child relationships. E.g.:

my $str = "One:Two:Three:four, One:Two:3:4, One:2:3:4, One:2:three";

should result in

$keywords = { One => { Two => { Three => four, 3 => 4 }, 2 => { 3 => 4, three => "" } } };

Though it should go without explanation, the idea is that "One" is the parent node to everything. It has two children, "Two" and "2". Each of those has children, who are either leaves or have their own children....

My current implementation is to split each comma-delimeted token along the :'s, and then call itself recursively to build the hash. I'm sooooo close, but it's just not getting it. I don't want to post my code so far so as to avoid influencing a better, more efficient method... you know how it goes: you work on something too long, and you can't see the forest for the trees anymore, and you doubt whether you went about it right in the first place.

The routine to test whether it works is here:

my $n = 0; sub print_keywords { my $k = shift; for my $key (keys %$k) { print " " x $n; print "$key\n"; $n++; if (keys %{$k->{$key}}) { print_keywords($k->{$key}); } elsif ($k->{$key}) { print " " x $n, $k->{$key}, "\n"; } $n--; } }

And, of course, you call it with the top of the hash returned after the parsing is done:

print_keywords($keywords);


In reply to parsing a parent-child syntax to make a hash by argv

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.