Skip to content

Instantly share code, notes, and snippets.

@danieljoos
Last active February 6, 2021 07:32
Show Gist options
  • Save danieljoos/08cb27106193e1210e67 to your computer and use it in GitHub Desktop.
Save danieljoos/08cb27106193e1210e67 to your computer and use it in GitHub Desktop.
Flatten a hash structure in plain Perl
# Helper routine for flattening a hash structure
sub flatten {
my ($h, $r, $p) = @_; $r = {} if not $r; $p = '' if not $p;
my $typed; $typed = sub {
my ($v, $p) = @_;
if (ref $v eq 'HASH') { flatten($v, $r, $p.'.'); }
elsif (ref $v eq 'ARRAY') { foreach(0..$#$v) { $typed->(@$v[$_], $p.'['.$_.']'); } }
else { $r->{$p} = $v; }
};
foreach (keys %$h) { $typed->($$h{$_}, $p.$_); };
return $r;
}
@sneharudravaram
Copy link

how do i modify the subroutine to get the output i want?

input:
my $data = {
bar => {cmd_opts => { gld_upf => ['abc' , 'def'] , rev_upf => ['123' , '456'] , temp => 'a'}},
};
output with current subroutine:
$VAR1 = {
'bar.cmd_opts.temp' => 'a',
'bar.cmd_opts.gld_upf[0]' => 'abc',
'bar.cmd_opts.gld_upf[1]' => 'def',
'bar.cmd_opts.rev_upf[0]' => '123',
'bar.cmd_opts.rev_upf[1]' => '456'
};

desired output:
$VAR1 = {
'bar.cmd_opts.temp' => 'a',
'bar.cmd_opts.gld_upf' => ['abc', 'def']
'bar.cmd_opts.rev_upf' => ['123', '456']
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment