Also consider the following hash of process_data:%files_data = { './GetOpt.pm' => { 'pid' => { '56061' => 1, '56065' => 1 } }, 'file1' => { 'pid' => { '56061' => 2 } }, 'file2' => { 'pid' => { '56065' => 2 } }, './src/bin/perl' => { 'pid' => { '56061' => 1, '56065' => 1 } } };
I would like to iterate through the `$files_data` hash and for each file get the chain of files.%process_data = ( '56061' => { 'parent' => 'NA', 'name' => 'file1' }, '56069' => { 'parent' => '56065', 'name' => 'echo Hello_file1' }, '56062' => { 'parent' => '56061', 'name' => 'echo Hello_file2' }, '56065' => { 'parent' => '56061', 'name' => 'file2' } );
I need to follow the pid chain up to the main parent ('NA') for each file.%hash = ( 'file1' => { '/src/bin/perl' => 1, 'file2' => { '/src/bin/perl' => 1, './GetOpt.pm' => 1 }, './GetOpt.pm' => 1, } );
Combine it:file1 => file2 => ./GetOpt.pm
I would like to build a process file chain (only with files). the `%files_data` contains valid files and `%process_data` contains the hierarchy of the process we need to follow.file1 => { ./GetOpt.pm, file2 => ./GetOpt.pm }
It does not quite do what I want. The hierarchy is not valid. I'm not sure what is wrong with the algorithm, it feels like true but the output is not as expected.create_proc_tree(\%process_data,\%files_data); sub create_proc_tree { my ($proc_href,$files_href) = @_; my %hash; while (my ($file, $procs) = each %{$files_href}) { foreach my $pid (keys(%{$procs->{'pid'}})) { my $prev_file = $file; do { my $parent_id = $proc_href->{$pid}{parent}; my $parent_name = $proc_href->{$pid}{name}; if ($prev_file eq $parent_name) { $hash{$parent_name} = 1; } else { $hash{$parent_name} = { (%{ $hash{$prev_file} // { +} }, $prev_file) }; delete($hash{$prev_file}); } $prev_file = $parent_name; my $parent_name = $proc_href->{$parent_id}{name}; } while(defined($parent_name)); } } print Dumper(\%hash); # Printing for debug }
Maybe a better approach will be to build a string like and then convert it to hash (although I read a comment saying that it is a bad why to use eval).use Data::Dumper; $abc = "Mouse=>Jerry, Cat=>Tom, Dog=>Spike"; my %hash = eval( "( $abc )" ); print Dumper(\%hash);
In reply to Reorganizing hash by ovedpo15
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |