Skip to content

Instantly share code, notes, and snippets.

@kazuho
Created June 13, 2014 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/c467462540d26d598478 to your computer and use it in GitHub Desktop.
Save kazuho/c467462540d26d598478 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Data::Dump qw(dump);
sub parse {
my $k = shift;
my @keys;
while (1) {
if ($k =~ s/\[([a-zA-Z_-]+)\]\z//) {
unshift @keys, $1;
} elsif ($k =~ s/\[\]\z//) {
unshift @keys, '';
} else {
unshift @keys, $k;
last;
}
}
return @keys;
}
sub _set {
my ($slot, $key, $v) = @_;
if ($key ne '') {
$slot = $slot->{$key} ||= $v;
} else {
push @$slot, $v;
$slot = $v;
}
return $slot;
}
sub set_value {
my ($slot, $k, $v) = @_;
my @keys = parse($k);
while (@keys) {
my $key = shift @keys;
$slot = _set($slot, $key, @keys ? $keys[0] ne '' ? +{} : +[] : $v);
}
}
sub expand_nested_params {
my $ary = shift;
my $ret = +{};
while (my ($k, $v) = splice @$ary, 0, 2) {
set_value($ret, $k, $v);
}
return $ret;
}
my $ret = expand_nested_params([
scalar1 => 'abc',
scalar2 => 'def',
q(array[]) => 1,
q(array[]) => 2,
q(array[][abc]) => 'hi'
]);
dump($ret);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment