I have a string that I would like to "unflatten" or "tree-ify"; that is, I want to go from this:
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,
}
My strategy was to process each field with delimiters separately and split into characters =into a key / value pair:
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;
}
I am trying recursive magic in processline:
sub processline {
my ($key) = @_;
my ($first, $rest) = split /_/, $key, 2;
if($rest) {
return { $first => &processline($rest) };
}
else {
return $first;
}
}
Unfortunately this does not work:
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);
When I do this, I get:
$VAR1 = {
'F' => '8',
'HASH(0xe9af60)' => '2',
'HASH(0xe9ae28)' => '11',
'E' => '5',
'HASH(0xe9af90)' => '3',
'HASH(0xe9ae40)' => '2'
};
Can someone explain the thought process for a recursive solution, or suggest where my Perl went so badly? Disappointingly, I could easily handle this function (smooth out).