in reply to Re: trouble with each and a hash of hashes
in thread trouble with each and a hash of hashes

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

Replies are listed 'Best First'.
Re^2: trouble with each and a hash of hashes
by jdalbec (Deacon) on Sep 11, 2004 at 14:42 UTC
    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
        As ccn quoted
        There is a single iterator for each hash, shared by all each, keys, and values function calls in the program; it can be reset by reading all the elements from the hash, or by evaluating keys HASH or values HASH.
        So if at all unsure just do
        keys %{$patterns{$gen}})
        before the while loop.
        But, why does this not happen every time the subroutine is called -- just once in a while?
        Is it possible that you sometimes return from the subroutine from inside the while loop?
Re^2: trouble with each and a hash of hashes
by CountZero (Bishop) on Sep 11, 2004 at 13:56 UTC
    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