2015-01-08 90 views
1

取值後創建圖表我在Perl代碼時,我直接拿值的Perl通過STDIN

$graph = { 
    'A' => {'B' => 1, 'C' => 5}, 
    'B' => {'C' => 4, 'D' => 2}, 
    'C' => {'A' => 1, 'B' => 3}, 
    'D' => {'C' => 2, 'B' => 3} 
}; 

這完美的作品,但我輸入的是這種格式

A B 1 
A C 5 
B C 4 
B D 2 
C A 1 
C B 3 
D C 2 
D B 3 

如何改變此輸入圖

回答

4

您可能想要檢查HoH世代。

use strict; 
use warnings; 

my $graph = {}; 
while (<DATA>) { 
    my ($k1, $k2, $val) = split; 
    $graph->{ $k1 }{ $k2 } = $val; 
} 

__DATA__ 
A B 1 
A C 5 
B C 4 
B D 2 
C A 1 
C B 3 
D C 2 
D B 3