Hello gregory-nisbet,

IIUC, a straightforward way to get the desired behaviour is to change this line:

%$hash_ref or return;

— which, if %$hash_ref is undefined may return either undef or () (the empty list), depending on whether the subroutine is called in scalar or list context — to this:

%$hash_ref or return undef;

BTW, I get the same results with this line:

keys %$hash_ref; # reset iterator

commented-out. Why do you think it’s useful here?

Anyway, hope that helps,

Update 1: It seems I missed the point of your question, which is “What's the idiomatic way to guard against unintentionally expanding a non-singleton list into the bodies of your hashes?” I think your own solution, to “use an intermediate scalar variable” is probably the best way.

Update 2: Alternatively, you could combine your suggestion of using the first element with a test for definedness:

18:30 >perl -MData::Dump -wE "sub f { return (17, 42); } my %h = ( key +1 => (f())[0] // undef ); dd \%h;" { key1 => 17 } 18:30 >perl -MData::Dump -wE "sub f { return (); } my %h = ( key +1 => (f())[0] // undef ); dd \%h;" { key1 => undef } 18:30 >

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: Preventing unintended list expansion inside hash literals. by Athanasius
in thread Preventing unintended list expansion inside hash literals. by gregory-nisbet

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.