Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by Anonymous Monk
on Nov 12, 2000 at 12:40 UTC ( [id://41166]=perlquestion: print w/replies, xml ) Need Help??

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

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

Originally posted as a Categorized Question.

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

Replies are listed 'Best First'.
Re: How do I print a hash so that it represents actual table with column headers?
by Fastolfe (Vicar) on Nov 12, 2000 at 13:36 UTC
    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}; }
      To get a slice from %$hash of keys @keys, use @$hash{@keys}, which can easily be derived from the more general form of @{...HASHREF...}{...keys-in-list-context...}.

      -- Randal L. Schwartz, Perl hacker

Re: How do I print a hash so that it represents actual table with column headers?
by toolic (Bishop) on Sep 01, 2009 at 01:51 UTC
    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;
Re: How do I print a hash so that it represents actual table with column headers?
by CharlesClarkson (Curate) on Jun 11, 2001 at 13:33 UTC

    In response to the note above:

    my %tmp = %{$hash{$key}}; printf($format, $key, @tmp{@keys});

    Could be rewritten as:

    printf($format, $key, @{$hash{$key}{@keys});

    Originally posted as a Categorized Answer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://41166]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-25 21:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found