user578086 user578086 - 3 years ago 167
Perl Question

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?

Answer Source

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};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download