Limo has asked for the wisdom of the Perl Monks concerning the following question:

How could I print a hash of arrays, like:
key1 key2 key3 ==== ==== ==== value value value | | | v v v
The number of keys will vary, depending upon input to the program.

Replies are listed 'Best First'.
Re: Structured Printing of Hash of Arrays
by merlyn (Sage) on Oct 12, 2000 at 01:08 UTC
    Untested, assuming %TOP for the top...
    my @keys = sort keys %TOP; my $format = join(" ", ("%20s") x @keys)."\n"; printf $format, @keys; for my $line (0..$#{$TOP{$keys[0]}}) { printf $format, map {$TOP{$_}[$line]} @keys; }

    -- Randal L. Schwartz, Perl hacker

      I was just going to mention that "%-20s" is probably more what was wanted than "%20s" (yes, annoying how printf defaults to right-justifaction for non-numeric formats). Then I noticed no double underlines and that you assume that all of the arrays have the same number of elements. Finally, I went with "%-19s" which fits nicely on screens that are a multiple of 20 characters wide.

      my @keys= sort keys %TOP; my $format= join( " ", ("%-19s") x @keys ) . "\n"; printf $format, @keys; printf $format, map { "=" x length($_) } @keys; my $line= 0; while( grep { $line <= $#{$TOP{$_}} } @keys ) { printf $format, map { def($TOP{$_}[$line]) } @keys; $line++; } sub def { return defined $_[0] ? $_[0] : def($_[1],""); }

              - tye (but my friends call me "Tye")
(jcwren) RE: Structured Printing of Hash of Arrays
by jcwren (Prior) on Oct 12, 2000 at 01:09 UTC
    Well, you didn't specify whether you meant as a dynamic screen display, or if you want to print to a file or printer. AgentM's answer is good for a dynamic display. If you want report-style output, there was a recent thread about using the format functions in Perl. Start looking here, at Using formats for 2-columnprinting

    --Chris

    e-mail jcwren
RE: Structured Printing of Hash of Arrays
by AgentM (Curate) on Oct 12, 2000 at 01:05 UTC
    Give Curses or ncurses (linux) a whirl. Someone else will most certainly post some complicated algorithm to organize your data. But when I see some text-display problems, I automatically reach for curses. It's insanely easy to use and learn. You'll be using some move() commands.
    AgentM Systems or Nasca Enterprises is not responsible for the comments made by AgentM- anywhere.