我有一个日志文件,如下所示。
Year:2001
State: A
District A
District B
State: B
District A
District B
Year:2002
State: A
District A
District B
State: B
District A
District B
.
.
Year:2012
State: A
District A
District B
State: B
District A
District B
我想要散列哈希,以便:
$VAR2 = {'2001' => {
'state A' => { district a
district b
}
'state B' => { district a
district b
}
}
2002' => {
'state A' => { district a
district b
}
'state B' => { district a
district b
}
}
};
我使用3个嵌套循环尝试了上述逻辑,如下所示:
foreach my $key (keys %hash) {
foreach my $key2 (keys %{ $hash{$key} }) {
foreach my $key3 (keys %{ $hash{$key}{$key2} }) {
$value = $hash{$key}{$key2}->{$key3};
}
}
}
请有人向我解释这样做的程序。或者至少告诉我,如果我要进入写入路径。谢谢。
答案 0 :(得分:1)
您可以执行以下操作:
use strict;
use warnings;
use 5.010;
use Data::Dumper;
my $hash;
my $year;
my $state;
while(<DATA>) {
chomp;
if(/^Year:(\d+)/) {
$year = $1;
$hash->{$year} = {};
next;
} elsif (/^State:/) {
$state = $_;
$hash->{$year}{$state} = [];
next;
} elsif(/^District/) {
push @{$hash->{$year}{$state}}, $_;
}
}
say Dumper$hash;
__DATA__
Year:2001
State: A
District A
District B
State: B
District A
District B
Year:2002
State: A
District A
District B
State: B
District A
District B
Year:2012
State: A
District A
District B
State: B
District A
District B
<强>输出:强>
$VAR1 = {
'2002' => {
'State: B' => [
'District A',
'District B'
],
'State: A' => [
'District A',
'District B'
]
},
'2001' => {
'State: B' => [
'District A',
'District B'
],
'State: A' => [
'District A ',
'District B'
]
},
'2012' => {
'State: B' => [
'District A',
'District B'
],
'State: A' => [
'District A ',
'District B'
]
}
};