2013-08-21 60 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如果?之前的聲明爲真,則該值爲?:之間的值。否則,該值是:之後的值。