You need two passes, one to build a list of sub-keys, and a second to print the table. Consider:

use strict; my %hash = ( Downtown_Market => {Fruit => 1, More_fruit => 2, Even_more_fruit = +> 3}, Uptown_market => {More_fruit => 4, Fruit => 5}, East_market => {Even_more_fruit => 6}, ); my %columnLookup; my @columns; my $maxKeyLen = 0; # Build list of sub-keys for my $key (keys %hash) { $maxKeyLen = length $key if length $key > $maxKeyLen; for my $subKey (keys %{$hash{$key}}) { next if exists $columnLookup{$subKey}; $columnLookup{$subKey} = @columns; push @columns, $subKey; } } # Print the table for my $key (sort keys %hash) { printf "%-*s (", $maxKeyLen + 2, "$key :"; print join ', ', map {exists $hash{$key}{$_} ? $_ : ' ' x length $_} @columns; print ")\n"; }

Prints:

Downtown_Market : (Even_more_fruit, More_fruit, Fruit) East_market : (Even_more_fruit, , ) Uptown_market : ( , More_fruit, Fruit)

Perl is environmentally friendly - it saves trees

In reply to Re: Print from HoH, in defined order, skipping missing keys by GrandFather
in thread Print from HoH, in defined order, skipping missing keys by BioNrd

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.