Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Preventing unintended list expansion inside hash literals.

by Athanasius (Archbishop)
on Jan 05, 2017 at 08:08 UTC ( [id://1178989]=note: print w/replies, xml ) Need Help??


in reply to Preventing unintended list expansion inside hash literals.

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,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1178989]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-23 23:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found