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?

( #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? 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}; }

Comment on Answer: How do I print a hash so that it represents actual table with column headers?
Select or Download Code
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 wandering the Monastery: (6)
As of 2014-09-16 12:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (15 votes), past polls