Skip to content

Instantly share code, notes, and snippets.

@kfly8
Last active August 29, 2015 14:06
Show Gist options
  • Save kfly8/965c316b250e787f499f to your computer and use it in GitHub Desktop.
Save kfly8/965c316b250e787f499f to your computer and use it in GitHub Desktop.
'a.b.c' => 1 # -> { a => { b => {c => 1}}}
#!/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;
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