user578086
user578086

Reputation: 331

Perl output array of hashes as table

If you have a array of hashes where the key represents the column name and the value is the row content what would be the best way to output this as a table in perl?

Upvotes: 4

Views: 1741

Answers (2)

Narveson
Narveson

Reputation: 1111

Does each row have the same hash keys? That's the structure you would get, e.g. from DBI, corresponding to the generally understood properties of tables (i.e. each row has the same set of columns). Here's a sample of what I have in mind, and I hope it matches what you're thinking:

my @AoH = (
    {id => 1, name => 'Dick'},
    {id => 2, name => 'Jane'},
);

In such cases you normally know what the columns are. I'm going to make that assumption. Here, then, is the code:

my @cols = qw(id name);
my @AoH;                 # as above

# print the column headings
print join "\t", @cols;

# print values for each row using a hash slice
for my $row_ref (@AoH) {
    print join "\t", @$row_ref{@cols};
}

Upvotes: 2

Pedro Silva
Pedro Silva

Reputation: 4710

Like this?

my @AoH = (
    {a => 1, b => 2},
    {c => 3, d => 4},
);

This maps to an N-dimensional table, where N is the number of elements in the array. You can't really visualize it for more than N = 3, unless you collapse the hashes (ie, make it all one big hash.)

If you just mean tabulate a 'reversed' hash, just transpose it:

my %a = (a => 1, b => 1);

my %b = map { $a{$_} => $_ } keys %a;

while ( my ($k, $v) = each %b ) {
    printf( "%s %s\n", $k, $v );
}

Upvotes: 1

Related Questions