CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [zohman] recursive subroutine for constructing hash: Edit Log



Zhris
Enthusiast

Apr 24, 2016, 12:23 PM


Views: 4097
Re: [zohman] recursive subroutine for constructing hash

Its been explained that this is possibly an xy problem and that your input and output data structures might be poorly designed. Nonetheless here is a recursive routine that returns your desired output structure:


Code
use strict; 
use warnings;
use Data::Dumper;

my $ref =
{
'su_u_av_fc_rel' => '(-,ebenzin1,) (-,nmigdal,)',
'skl_rtl_users__n72' => 'skl_rtl_users__n14 skl_rtl_users__n15 skl_rtl_users__n56 sys_triple_group',
'skl_rtl_users__n15' => '(-,dbenita,) (-,dbenner,) (-,dbenyose,) (-,dbgurura,)',
'skl_rtl_users__n14' => '(-,csmithhi,) (-,csnguyen,) (-,csnider,) (-,csoni,)',
'skl_rtl_users__n56' => '(-,sgluxman,) (-,sgoh9,) (-,sgoldenb,) (-,sgollapu,)',
'sys_rh_alldisks' => 'sys_rh_backup sys_rh_rsync sys_rh_start sys_triple_group',
'sys_rh_backup' => '(iillsbk0100,-,) (iillsbk0101,-,)',
'sys_rh_rsync' => 'sys_rh_rsync__n1 sys_rh_rsync__n2 sys_triple_group sys_rh_nis3',
'sys_rh_nis3' => 'sys_rh_nis33 sys_rh_nis32',
'sys_triple_group' => '(icsl0945,-,)',
'sys_rh_rsync__n1' => '(icsl0944,-,) (icsl0945,-,) (icsl2878,-,)',
'sys_rh_rsync__n2' => '(irsync107,-,) (irsync108,-,)',
'sys_rh_nis33' => '(sync107,-,) (irsy8,-,)',
'coe73_users__n53' => '(-,wwang69,) (-,wwong23,) (-,wwong5,) (-,wwong8,) (-,wwsee,) (-,wyeohx,) (-,wyuan,) (-,xdang,) (-,xiaomin2,)',
'sys_rh_nis32' => '(irserer7,-,) (irsrrt8,-,)',
'iclbuild' => '(biur7,-,) (biur9,-,) (biur10,-,) (biur11,-,) (biur12,-,) (biur13,-,)',
'sys_rh_start' => '(iinf069,-,) (iinf157,-,)'
};

print Dumper recurse( $ref );

sub recurse
{
my ( $in, $keys ) = @_;

$in // die 'in required';
$keys //= [ keys %$in ];

my $out = { };

for my $key ( @$keys )
{
my $val = $in->{$key};

if ( $val !~ m/\(/ )
{
my $next_keys = [ split ' ', $val ];

$out->{$key} = recurse( $in, $next_keys );
}
else
{
$out->{$key} = $val;
}
}

return $out;
}


Chris


(This post was edited by Zhris on Apr 24, 2016, 12:24 PM)


Edit Log:
Post edited by Zhris (Enthusiast) on Apr 24, 2016, 12:24 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives