Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

How do I print a hash so that it represents actual table with column headers?

( #41166=categorized question: print w/ replies, xml ) Need Help??
Contributed by Anonymous Monk on Nov 12, 2000 at 12:40 UTC
Q&A  > hashes


Answer: How do I print a hash so that it represents actual table with column headers?
contributed by Fastolfe

A hash only contains keys and values, so I'm not sure what sort of header you'd want. Perhaps printf can be of use:

printf "%20s %s\n", "Key", "Value"; printf "%20s-%s\n", "-"x20, "-----"; foreach my $key (keys %hash) { printf "%20s %s\n", $key, $hash{$key}; }
If you're talking about a more complex data structure (such as a homogenous hash of hashes), perhaps something more like this would be to your liking:
# $hash{$key} = { field1 => 'value', ... }; my @keys = keys %{$hash{(keys %hash)[0]}}; my $format = "%10s " . ("%10s " x @keys) . "\n"; printf $format, "Key", @keys; foreach my $key (keys %hash) { printf $format, $key, @{$hash{$key}}{@keys}; }
Answer: How do I print a hash so that it represents actual table with column headers?
contributed by toolic

Text::Table can be used to format the keys and values of a simple hash as a 2-column table. It automatically calculates the width of each column.

use Text::Table; my $tb = Text::Table->new(qw(Keys Values)); # column headers for my $k (keys %hash) { $tb->add($k, $hash{$k}) } print $tb;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others having an uproarious good time at the Monastery: (10)
    As of 2014-08-20 17:25 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The best computer themed movie is:











      Results (120 votes), past polls