So why can't I be Lazy and do this?
Because you're trying to dereference the hash that $obj->method returns, which won't work seeing as how it's already a hash. You could just change your code so that you can dereference your return value e.g
# assuming $obj->{attr_name} holds a hashref return $obj->{attr_name}; } # code passes foreach my $item (keys %{ $obj->method() }) {
My guess is that the hash gets flattened into list context by the return and somehow doesn't get coerced back into a hash by the keys function
A hash is indeed flattened to a list in list context, which is provided by your hash assignment in your second example. However keys expects a % sigil, so while you are returning a hash1 from $obj->method keys is none the wiser. So you have to enforce the sigil by either using a hash or dereferencing a hashref e.g
my %hash = qw(foo bar baz quux); my $hashref = \%hash; my @list = qw(ichi ni san shi); my $lisref = \@list; keys %hash; # valid keys %$hashref; # valid keys %{{@list}}; # valid keys %{{@$listref}}; # valid keys $hashref; # invalid keys %{@list}; # invalid

HTH

_________
broquaint

update: added further clarification about hashes
1 you're not really returning a hash, just a list which is being stuffed into a hash


In reply to Re: iterating returned hashes by broquaint
in thread iterating returned hashes by biketastic

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.