in reply to Re^2: Nested while each over a hash -> infinite loop
in thread Nested while each over a hash -> infinite loop

My original post has been updated with some code to show how to do what you probably intended to do. Have a look. I think it will get you back on track. You may need to browse over one or more of the following: perlreftut, perllol, and perldsc.


Dave

  • Comment on Re^3: Nested while each over a hash -> infinite loop

Replies are listed 'Best First'.
Re^4: Nested while each over a hash -> infinite loop
by Eythil (Acolyte) on Jun 10, 2011 at 08:39 UTC
    I think I should explain my problem a bit more in detail: I have a hash like
    my $test = ( 'a' => { 'identifiers' => { 'mrt1' => 1, 'mrt2' => 1, 'mrt3' => 1, }, }, 'b' => { 'identifiers' => { 'mrt2' => 1, 'mrt3' => 1, 'mrt6' => 1, }, }, 'c' => { 'identifiers' => { 'mrt1' => 1, 'mrt2' => 1, 'mrt3' => 1, }, }, 'd' => { 'identifiers' => { 'mrt2' => 1, 'mrt3' => 1, 'mrt6' => 1, }, }, 'sum_ab' => { 'values' => { 'a' => 1, 'b' => 1, }, }, 'sum_cd' => { 'values' => { 'c' => 1, 'd' => 1, }, }, 'sum_abcd' => { 'values' => { 'sum_ab' => 1, 'sum_cd' => 1, }, }, );
    In case of mrt1 I do something, because a is matched. Afterwards I need to do something, because sum_ab has a in its 'values'-hash. Afterwards I have to check if some sum includes 'sum_ab' and so on...

    That is the reason, why I wanted to use the nested iteration over the same hash. Perhaps I could push to some temporary variable and do the second while after the first one.

      So you would benefit here from recursion:

      traverse(\%my_hash); sub traverse { my $hash_ref = shift; while ( my( $key, $value ) = each %{ $hash_ref } ) { if( ref $value ) { traverse( $value ); } else { print "$key => $value\n"; } } }

      Dave

        Sorry for sending you a message earlier. Actually that should have been a reply to the thread

        Recursion is indeed the solution to my problem. Thank you very much.

      In what way was my sample code inadequate?


      Dave