From the documentation for each:

After each has returned all entries from the hash or array, the next call to each returns the empty list in list context and undef in scalar context. The next call following that one restarts iteration.

The outer while loop grabs the only element in %test. The inner while loop gets an empty list, and consequently never executes. So the outer while loop tests each again. This time it has reset, so it again returns the first (and only) element from %test.

Nothing wrong with Perl. Your script is flawed.

Also, if you were using use strict; at the top of your script you would have discovered that print $name1 is not working out so well, since there is no $name1. The outer loop creates $name, not $name1. Furthermore, your code won't even compile as your outer while loop's parens don't nest properly.

You may want something more like this:

use strict; use warnings; my %test = ('a' => {'b' => 'b'}); while ( my ( $name, $value ) = each %test ) { print $name; while ( my ( $name2, $value2 ) = each %{ $value } ) { print $name2; } }

Dave


In reply to Re: Nested while each over a hash -> infinite loop by davido
in thread Nested while each over a hash -> infinite loop by Eythil

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.