perl - Searching within Hash of Hashes -


say have array , multidimensional hash. want recursively whether values in array exist keys in hash. there better way doing follows? (example edited perl mavenperl maven).

note couple of things more:

  1. in example below, foobar , mathematics exist in hash %grades;
  2. the main question in post how find more efficient way search @ first level, second level, etc. etc., given real example has 7 levels;
  3. note that, idea try tighten search possible. best if elements in array found, order, in hash (i.e. having @array=("foobar","mathematics") values @ $myhash{"foobar"}{"mathematics"}; if fails, whether "foobar" or "mathematics" exist @ second level of hash, i.e. $myhash{"otherkeys"}{"mathematics"} or $myhash{"otherkeys"}{"foobar"}).

example:

#!/usr/bin/perl use strict; use warnings; use data::dump; @subjectsandnames=("foobar","thatbar","mathematics","biology","physics"); %grades;  $grades{"foobar"}{mathematics}   = 12; $grades{"foobar"}{literature}    = 99; $grades{"petibar"}{literature}   = 87; $grades{"petibar"}{mathematics}  = 13; $grades{"petibar"}{art}          = 93; foreach $name (sort keys %grades) {     @possible = grep defined, map { $grades{$_}} @subjectsandnames; #sees matches @ first level     dd @possible;         foreach $subject (sort keys %{$grades{$name}}){         @possible2 = grep defined, map { $grades{$name}{$_}} @subjectsandnames; #sees matches @ second level         dd @possible2;     } } 

not knowing data , situation in detail, makes difficult give complete advice.

however, wanted see if deepest level key equal 1 of list of subjects. recursing hash of hashes possible solution demonstrated below:

#!/usr/bin/perl use strict; use warnings; use data::dump;  @subjectsandnames = qw(foobar thatbar mathematics biology physics);  %grades = (     foobar => {         mathematics => 12,         literature  => 99,         },     petibar => {         literature  => 87,         mathematics => 13,         art         => 93,         },     );  recurse_hash(\%grades);  sub recurse_hash {     ($hashref, @keys) = @_;      $key (sort keys %$hashref) {         $val = $hashref->{$key};         if (ref $val) {             recurse_hash($val, @keys, $key);         } elsif (grep {$key eq $_} @subjectsandnames) {             print "@keys $key $val\n";         }     } } 

outputs:

foobar mathematics 12 petibar mathematics 13 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -