Hello all -

I've got a problem using the result of a function which has the following behaviour: When it is called in list context, it returns a hash; but when it is called in scalar context, it returns a reference to a hash. My problem relates to the second case, when the result of the function call is used in a 'while .... each ...' construct. Here is the example code:

use warnings; use strict; sub e() { my %result=(A=>1,B=>2); wantarray ? %result : \%result; } my %env=e; $|=1; while (my ($var,$val) = each %env) { print "(hash) $var=$val\n"; } while (my ($var,$val) = each %{ &e }) { print "(ref) $var=$val\n"; }
The first while works fine. %env was set by calling e in list context, and it is the hash. The second while loops forever, returning the same element of the hash all the time.

My reasoning was as follows: Inside %{...}, the call to e is done in a scalar context, so it should return the reference to the hash, which then would be passed to each. The call to each in turn is in list context, so we should iterated over the hash. However, it looks as if the iterator would be reset every time.

Could someone explain to me, what is going on her and why, and how to properly iterate over a hash given a hash reference? Well, I can of course use the keys function, but I wonder whether it is possible to do with each.

-- 
Ronald Fischer <ynnor@mm.st>

In reply to This "each" goes to endless loop each time... by rovf

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.