Last active
February 6, 2021 07:32
-
-
Save danieljoos/08cb27106193e1210e67 to your computer and use it in GitHub Desktop.
Flatten a hash structure in plain Perl
This file contains 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
# 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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']
}