我需要在Perl中创建依赖哈希。 program1取决于program2 program4 program10 program5 program7 program6等。数据是随机生成的,例如:
#!/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)
将数据减少到以下内容可以更有效地检查问题:
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} ||= {};
}
}