http://www.perlmonks.org?node_id=1178987

gregory-nisbet has asked for the wisdom of the Perl Monks concerning the following question:

=> and , both impose list context on their arguments in the body of hash table since it's an ordinary list expression. This can have unintended consequences in cases like this.

Suppose we have a function that takes an arbitrary key from a hash reference. However, when the hash table is empty, we just call return. Most of the time we're calling this function in scalar context, so we're fine.

sub some_key { my $hash_ref = shift; %$hash_ref or return; my ($key, undef) = each %$hash_ref; keys %$hash_ref; # reset iterator $key; }

However, one day, we decide to use it to construct a value in a hash table (or key, argument is the same).

my %some_hash = ( key1 => some_key($bar), key2 => some_key($baz), );

If $bar and $baz are both empty, then we now have %some_hash = (key1 => 'key2');, which almost certainly wasn't intended.

It's clear what happened. Most of the time some_key returns a list with one element, and we treated it as if it always does.

In my own code I avoid explicitly creating keys or values from the return values of subroutines and use an intermediate scalar variable instead, unless my expression is guaranteed to be a single-element list in list context like $array_ref->[0], [function()], or $hash{$key}. Note though that (...)[0] is a zero-element list in list context if the list is empty.

What's the idiomatic way to guard against unintentionally expanding a non-singleton list into the bodies of your hashes? I haven't seen anything about it specifically in style guides so far.