Last active
August 29, 2015 14:06
-
-
Save kfly8/965c316b250e787f499f to your computer and use it in GitHub Desktop.
'a.b.c' => 1 # -> { a => { b => {c => 1}}}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use 5.10.0; | |
use strict; | |
use warnings; | |
use utf8; | |
use Test::More; | |
sub merge { | |
my ($a, $b) = @_; | |
while (my ($k, $v) = each %$b) { | |
if (ref $v) { | |
$a->{$k} //= +{}; | |
merge($a->{$k}, $v); | |
} | |
else { | |
$a->{$k} = $v; | |
} | |
}; | |
$a; | |
} | |
sub _hoge { | |
@_ == 1 ? shift : +{ shift() => _hoge(@_) } | |
} | |
sub hoge { | |
my $h = shift; | |
my $res = +{}; | |
while (my ($key,$val) = (each %$h)) { | |
$res = merge($res, _hoge( (split /\./, $key), $val)); | |
} | |
$res; | |
} | |
my $ORG = +{ | |
'a.b.c' => 1, | |
'a.b.d' => 'hello', | |
'e.f' => 'world', | |
'g' => 'apple', | |
#'a' => 'aaa', # ぬーん | |
}; | |
is_deeply hoge($ORG), +{ | |
a => +{ | |
b => +{ | |
c => 1, | |
d => 'hello', | |
}, | |
}, | |
e => +{ | |
f => 'world', | |
}, | |
g => 'apple', | |
}; | |
done_testing; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use utf8; | |
use Test::More; | |
sub merge { | |
my ($a, $b) = @_; | |
while (my ($k, $v) = each %$b) { | |
if (ref $v) { | |
$a->{$k} //= +{}; | |
merge($a->{$k}, $v); | |
} | |
else { | |
$a->{$k} = $v; | |
} | |
}; | |
$a; | |
} | |
sub hoge { | |
my $h = shift; | |
my $res = +{}; | |
while (my ($key,$val) = (each %$h)) { | |
my $sub; | |
my @keys = split /\./, $key; | |
while (my $k = pop @keys) { | |
$sub = +{ $k => ($sub ? $sub : $val) }; | |
} | |
$res = merge($res, $sub); | |
} | |
$res; | |
} | |
my $ORG = +{ | |
'a.b.c' => 1, | |
'a.b.d' => 'hello', | |
'e.f' => 'world', | |
'g' => 'apple', | |
#'a' => 'aaa', # ぬーん | |
}; | |
is_deeply hoge($ORG), +{ | |
a => +{ | |
b => +{ | |
c => 1, | |
d => 'hello', | |
}, | |
}, | |
e => +{ | |
f => 'world', | |
}, | |
g => 'apple', | |
}; | |
done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment