2013-08-21 59 views
1

的矩阵表格我有一个数据结构是这样的:印刷散列成在Perl

#!/usr/bin/perl -w 
my $hash = { 
      'abTcells' => { 
          'mesenteric_lymph_node' => { 
                 'Itm2a' => '664.661', 
                 'Gm16452' => '18.1425', 
                 'Sergef' => '142.8205' 
                 }, 

           'spleen'  => { 
                 'Itm2a' => '58.07155', 
                 'Dhx9' => '815.2795', 
                 'Ssu72' => '292.889' 

               } 
          } 
      }; 

我想要做的就是把它打印出来为这种格式:

   mesenteric_lymph_node  spleen 
Itm2a    664.661     58.07155 
Gm16452    18.1425     NA 
Sergef    142.8205    NA 
Dhx9     NA      815.2795 
Ssu72    NA      292.889 

什么要做到这一点。

我目前坚持用下面的代码https://eval.in/44207

foreach my $ct (keys %{$hash}) { 
    print "$ct\n\n"; 
    my %hash2 = %{$hash->{$ct}}; 
     foreach my $ts (keys %hash2) { 
     print "$ts\n"; 
     my %hash3 = %{$hash2{$ts}}; 
     foreach my $gn (keys %hash3) { 
      print "$gn $hash3{$gn}\n"; 
     } 
    } 
} 

回答

4

使用Text::Table输出。 Beautify to taste

#!/usr/bin/env perl 

use strict; 
use warnings; 

use Text::Table; 

my $hash = { 
    'abTcells' => { 
     'mesenteric_lymph_node' => { 
      'Itm2a' => '664.661', 
      'Gm16452' => '18.1425', 
      'Sergef' => '142.8205' 
     }, 
     'spleen' => { 
      'Itm2a' => '58.07155', 
      'Dhx9' => '815.2795', 
      'Ssu72' => '292.889' 
     } 
    } 
}; 

my $struct = $hash->{abTcells}; 

my @cols = sort keys %{ $struct }; 
my @rows = sort keys %{ { map { 
    my $x = $_; 
    map { $_ => undef } 
    keys %{ $struct->{$x} } 
} @cols } }; 

my $tb = Text::Table->new('', @cols); 

for my $r (@rows) { 
    $tb->add($r, map $struct->{$_}{$r} // 'NA', @cols); 
} 

print $tb; 

输出:现在

  mesenteric_lymph_node spleen 
Dhx9 NA     815.2795 
Gm16452 18.1425    NA 
Itm2a 664.661    58.07155 
Sergef 142.8205    NA 
Ssu72 NA     292.889

,上述行的顺序是比你展示,因为我希望它是一贯的不同。如果你知道所有可能的行的集合,那么你可以明确地指定另一个订单。

0

无论你内心的散列的按键相同,所以做的散列拿到钥匙的一个一个foreach,然后同时打印。

1

第一件事是分离出两个散列:

my %lymph_node = %{ $hash->{abTcells}->{mesenteric_lymph_node} }; 
my %spleen  = %{ $hash->{abTcells}->{spleen} }; 

现在,您有一个包含你想要的数据两个独立的哈希值。

我们需要的是所有键的列表。让我们制作第三个包含您的密钥的散列。

my %keys; 
map { $keys{$_} = 1; } keys %lymph_node, keys %spleen; 

现在,我们可以浏览所有的密钥并打印每个哈希的值。如果散列一个没有数据,我们将它设置为NA

for my $value (sort keys %keys) { 
    my $spleen_value; 
    my $lymph_nodes_value; 
    $spleen_value = exists $spleen{$value} ? $spleen{$value} : "NA"; 
    $lymph_node_value = exists $lymph_node{$value} ? $lymph_node{$value} : "NA"; 
    printf "%-20.20s %-9.5f %-9.5f\n", $key, $lymph_node_value, $spleen_value; 
} 

printf声明是tabularize数据的好方法。你必须自己创建标题。 ... ? ... : ...声明是缩写if/then/else如果?之前的声明为真,则该值为?:之间的值。否则,该值是:之后的值。