How do I recursively move the structure of nested hash data?

I am stuck in what seems to me a simple conceptual problem. After carefully searching for similar problems on the Internet and overflowing the stack, I couldn't find something like this, so I thought I might ask you.

I am creating a hash hash structure that is deeply nested. Depth can be 10-20 times. For the sake of this problem, I list only to the depth.

I cannot recursively go through the hash image of the sample below in Perl. I also included my code.

This gives me the following error:

It is not possible to use string ("1") as a HASH ref, while "strong links" are used when

It’s just so clear: my hash has certain keys with a value of 1. I cannot escape them.

$VAR1 = { 'Eukaryota' => { 'Rhodophyta' => {'count' => 5}, 'Alveolata' => {'count' => 16}, 'stramenopiles' => {'count' => 57}, 'count' => 155, 'Glaucocystophyceae' => {'count' => 1}, 'Cryptophyta' => {'count' => 18}, 'Malawimonadidae' => {'count' => 1}, 'Viridiplantae' => {'count' => 57}, }, 'Bacteria' => { 'Cyanobacteria' => {'count' => 1}, 'Actinobacteria' => {'count' => 4}, 'count' => 33, 'Proteobacteria' => {'count' => 25}, 'Deinococcus-Thermus' => {'count' => 2}, 'Firmicutes' => {'count' => 1}, }, }; 

Code to recursively pass this hash:

 sub analyse_contig_tree_recursively { my $TAXA_TREE = shift @_; my $contig_hash = shift @_; foreach (keys %{$TAXA_TREE}) { print "$_ \n"; analyse_contig_tree_recursively($TAXA_LEVEL->{$_}, $contig_hash); } } 
+6
source share
1 answer

I'm not sure what you are calling analyse_contig_tree_recursively on (you do not use this parameter $contig_hash anywhere and you did not define $TAXA_LEVEL : did you mean $TAXA_TREE ?), But there is obviously a mismatch between the layout of the data structure and yours recursive traversal pattern. The traversal function assumes that all entries are hashes and processes empty hashes as a completion case: if keys %{$TAXA_TREE} empty, there is no recursive call. Given your data, you need to check if the value is a hash or not, and not recursively if you don't consider it a hash.

 sub analyse_contig_tree_recursively { my $TAXA_TREE = shift @_; foreach ( keys %{$TAXA_TREE} ){ print "$_ \n"; if (ref $TAXA_TREE->{$_} eq 'HASH') { analyse_contig_tree_recursively($TAXA_TREE->{$_}); } } } 
+11
source

Source: https://habr.com/ru/post/889724/


All Articles