2016-08-23 91 views
0

我需要在Perl中創建依賴關係的散列。該程序1取決於從程序2 program4 program10 program5 program7 program6等數據是隨機例如生成:程序依賴的Perl嵌套散列

#!/usr/bin/env perl 

use strict; 
use warnings; 

use Data::Dumper; 
use English qw(-no_match_vars); 

my $dependsOrder = {}; 
while (my $line = <DATA>) { 
    chomp $line; 
    my ($component, $depends) = split /:/, $line; 
    if (exists $dependsOrder->{$component} and $dependsOrder->{$component} == 1) { 
     $dependsOrder->{$component} = {}; 
    } 
    if ($depends) { 
     $depends =~ s/^\s+|\s+$// if $depends; 
     my @depends = split /\s+/, $depends; 
     for my $dependency (@depends) { 
      if (not exists $dependsOrder->{$dependency}) { 
       # default value 
       $dependsOrder->{$dependency} = 1; 
      } 
      $dependsOrder->{$component}->{$dependency} = $dependsOrder->{$dependency}; 
     } 
    } 
    else { 
     $dependsOrder->{$component} = 1; 
    } 
} 
print Dumper $dependsOrder->{'program1'}; 
#print Dumper $dependsOrder->{'program6'}; 

__DATA__ 
program1: program2 program4 program10 program5 program7 program6 
program2: program7 program5 program9 program8 program10 program3 program6 program1 
program3: program2 program9 program8 
program4: program5 program8 program10 program1 program2 program2 program9 
program5: program3 program6 program4 program7 
program6: program5 program8 program7 
program7: program1 program2 program9 program10 
program8: program1 program9 program6 program10 program3 program2 
program9: 
program10: program6 program9 

此代碼不能真正工作:

$VAR1 = { 
      'program7' => 1, 
      'program10' => 1, 
      'program6' => 1, 
      'program2' => 1, 
      'program4' => 1, 
      'program5' => 1 
     }; 

但是,如果我改變了第22行:

$dependsOrder->{$dependency} = 1; 

有:

$dependsOrder->{$dependency} = {}; 

它工作正常,但我沒有默認值:

$VAR1 = { 
      'program7' => { 
          'program2' => { 
              'program8' => { 
                  'program9' => {}, 
                  'program6' => { 

什麼是錯誤的,我推理的默認值?

+0

是什麼'1'是什麼意思?爲什麼你想要默認值1? –

+1

如果存在循環依賴關係,您會期望做什麼?你的例子有一個(p1 - > p4 - > p1) –

+0

這只是一個想法。我需要依賴樹來對一系列程序進行排序。 這是錯誤的例子。事實上,我沒有循環依賴。 – piecia

回答

1

的數據減少了以下允許更有效地審查這個問題:

program1: program2 
program2: program7 

在第一種情況下,你做了什麼歸結爲

$d->{p2} = 1; 
$d->{p1}{p2} = $d->{p2};  # $d->{p1}{p2} = 1; 
$d->{p2} = {}; 
$d->{p7} = 1; 
$d->{p2}{p7} = $d->{p7};  # $d->{p2}{p7} = 1; 

$d->{p1}{p2}包含1 ,並且$d->{p2}包含對在最後一行中修改的散列的引用。


在第二種情況下,你做了什麼歸結下來到

$d->{p2} = {}; 
$d->{p1}{p2} = $d->{p2}; 
$d->{p7} = {}; 
$d->{p2}{p7} = $d->{p7}; 

$d->{p1}{p2}$d->{p2}含有相同的哈希值,這是在最後一行修改引用。


您的代碼也可以寫成如下:

my %dependency_tree; 
while (<DATA>) { 
    chomp; 
    my ($component, $depends) = split /:/; 
    $dependency_tree{$component} ||= {}; 
    for my $dependency (split ' ', $depends) { 
     $dependency_tree{$component}{$dependency} = 
      $dependency_tree{$dependency} ||= {}; 
    } 
}