我有一个想要“unflatten”或“tree-ify”的字符串;也就是说,我想从这个开始:
F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5
对此:
{
A => {
B => 2,
C => 3,
},
D => {
B => 2,
G => {
H => 11,
},
},
E => 5,
F => 8,
}
我的策略是分别处理每个以管道分隔的字段,并按=
符号拆分为键/值对:
sub unflatten {
my ($data) = @_;
my @fields = split /\|/, $data;
my $result = {};
for my $datum (@fields) {
my ($key, $value) = split /=/, $datum;
$result->{&processline($key)} = $value;
}
return $result;
}
我在processline
函数中尝试了一些递归魔法:
sub processline {
my ($key) = @_;
my ($first, $rest) = split /_/, $key, 2; # split key into at most 2 parts
if($rest) {
return { $first => &processline($rest) };
# if the key is nested, there will be something in $rest
# so recursively process the smaller $rest, and build up the result hashref
}
else {
return $first;
}
}
不幸的是,这不起作用:
my $header = "F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5";
use Data::Dumper;
print Dumper &unflatten($header);
当我这样做时,我得到:
$VAR1 = {
'F' => '8',
'HASH(0xe9af60)' => '2',
'HASH(0xe9ae28)' => '11',
'E' => '5',
'HASH(0xe9af90)' => '3',
'HASH(0xe9ae40)' => '2'
};
有人可以解释递归解决方案背后的思考过程,或者建议我的 Perl 哪里出了问题?令人沮丧的是,我能够很容易地想出这个函数的反函数(展平)。