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,