Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Answer: 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 ( #41171=categorized answer: print w/replies, xml ) Need Help??

Q&A > hashes > How do I print a hash so that it represents actual table with column headers? - Answer 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}; }

Replies are listed 'Best First'.
RE: Answer: How do I print a hash so that it represents actual table with column headers?
by merlyn (Sage) on Nov 12, 2000 at 16:56 UTC
    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

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 imbibing at the Monastery: (9)
As of 2016-09-26 16:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (484 votes). Check out past polls.