简体   繁体   English

Perl输出哈希数组作为表

[英]Perl output array of hashes as table

如果你有一个哈希数组,其中键表示列名,值是行内容,那么在perl中输出它作为表的最佳方法是什么?

Does each row have the same hash keys? 每行是否都有相同的哈希键? That's the structure you would get, eg from DBI, corresponding to the generally understood properties of tables (ie each row has the same set of columns). 这是您将获得的结构,例如来自DBI,对应于通常理解的表的属性(即每行具有相同的列集)。 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};
}

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. 这映射到N维表,其中N是数组中元素的数量。 You can't really visualize it for more than N = 3, unless you collapse the hashes (ie, make it all one big hash.) 你不能真正想象它超过N = 3,除非你折叠哈希(即,使它成为一个大哈希。)

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 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM