in reply to trouble with each and a hash of hashes

It must be something with the data in your hash or HOH.

The while will fall through when the assignment($s_pattern,$p_pattern) = each %{$patterns{$gen}} is false. This should normally only happen when you reach the "end" of your HOH.

foreach on the other hand will dutyfully churn through the whole of the array (keys returns an array of key-values) even if they are empty, undef or NULL. Strange as it may seem, but they the key-value of a hash can be empty and the value-value can be undef. Did you have a look at your data-structures with Data::Dumper? Always a great help to do!

Update: fixed a typo.

CountZero

"If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Replies are listed 'Best First'.
Re: trouble with each and a hash of hashes
by marcokuma (Novice) on Sep 11, 2004 at 13:48 UTC
    Thanks!

    I tried Data::Dumper, and things get weirder.

    If I print the hash with Data:Dumper, the problem disappears.

    So, in the following case sometimes while fails:
    while (($s_pattern,$p_pattern) = each %{$patterns{$gen}}) { # ... }
    But in the following case the while loop is always entered:
    print Dumper(%{$patterns{$gen}}); while (($s_pattern,$p_pattern) = each %{$patterns{$gen}}) { # ... }
    Nothing else changes!

    Mystery...

    Marco
      Are you using each before this in your program? Are you calling the subroutine twice in a row without making changes to the HoH in between? If the while loop is preceded chronologically by another while loop with the same structure that might explain why the second loop is being skipped.

      Data::Dumper probably resets the iterator and so it runs through the HoH normally. What happens if you change "print Dumper" to "keys"? Does it still cause the while loop to run?

        Thanks to everybody who gave me advice.

        Yes, I am calling the subroutine many times (once for each input line matching certain conditions).

        Yes, I do NOT change the HoH in between.

        Yes, if I use keys instead of print Dumper I get the same effect (things work).

        So, I guess the problem is that I need to reset the iterator.

        But, why does this not happen every time the subroutine is called -- just once in a while?

        Also, is there a standard way to reset the iterator?

        Thanks again.

        Marco
      And it is with exactly the same data each and every time?

      Strangeness abounds!

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law