Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2024-03-28 13:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found