in reply to Hash to HTML display

Not nicely indented, but close enough:
sub hash_to_html { my $x = shift; return "" unless ref($x) eq "HASH"; return "<ul>".join("", map { "<li>$_\n".hash_to_html($x->{$_}) } sor +t keys %$x )."</ul>\n"; } $our_hash = { 'Cows' => { 'Brown' => undef, 'Green' => undef, 'Strawberry' => { 'Spotted' => undef, 'Solid' => undef }, 'Orange' => undef }, 'Dogs' => { 'Purple' => { 'Spotted' => undef, 'Solid' => undef } } }; print hash_to_html($our_hash);
which generates:
<ul><li>Cows <ul><li>Brown <li>Green <li>Orange <li>Strawberry <ul><li>Solid <li>Spotted </ul> </ul> <li>Dogs <ul><li>Purple <ul><li>Solid <li>Spotted </ul> </ul> </ul>

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Hash to (X)HTML display
by flocto (Pilgrim) on Jul 18, 2002 at 11:01 UTC

    Maybe I'm a little too picky here, but I want to encourage everybody to write "right" HTML; with XHTML in mind, of course.. I edited merlyn's code so it creates XHTML conform output:

    sub hash_to_html ($;$) { my $x = shift; my $i = @_ ? shift : ''; return "" unless ref ($x) eq "HASH"; return "$i<ul>\n" . join ('', map { "$i <li>$_</li>\n" . hash_to_html ($x->{$_}, "$ +i ") } sort (keys (%$x))) . "$i</ul>\n"; }

    Which prints (with the input above):

    <ul> <li>Cows</li> <ul> <li>Brown</li> <li>Green</li> <li>Orange</li> <li>Strawberry</li> <ul> <li>Solid</li> <li>Spotted</li> </ul> </ul> <li>Dogs</li> <ul> <li>Purple</li> <ul> <li>Solid</li> <li>Spotted</li> </ul> </ul> </ul>

    Regards,
    -octo

      No, you've got the /LI in the wrong place. Change
      join ('', map { "$i <li>$_</li>\n" . hash_to_html ($x->{$_}, "$i " +) } sort (keys (%$x)))
      to
      join ('', map { "$i <li>$_\n" . hash_to_html ($x->{$_}, "$i ")."$i + </li>" } sort (keys (%$x)))

      -- Randal L. Schwartz, Perl hacker

        Oh, right.. I don't do lists all that often, but these not-closed li-tags just bugged me :)

        Regards, -octo

      but I want to encourage everybody to write "right" HTML
      Hmm. You are aware that in HTML, the close tag on an LI element is completely optional, and still validates? So it's "right" HTML. Truly. It's not tag soup with error correction. It really is "right" HTML.

      Surely it's not XHTML, but the rules are different there. No optional close tags, for example. And all your attributes must be quoted. And a few other miscellaneous things.

      But the original request was for HTML, so I kept my version of the program simple.

      -- Randal L. Schwartz, Perl hacker

Re: &bull;Re: Hash to HTML display
by Anonymous Monk on Jul 18, 2002 at 07:30 UTC
    Thanks a ton!

    I don't know what I'd do without you guys :)