Empty Hash Values

Matt Lawrence matt.lawrence at virgin.net
Sun Apr 12 20:09:43 BST 2009

Nigel Peck wrote:
> When I create a hash like this:
> my $hash = {
>     element_1 => 'example',
>     element_2 => $var,
>     element_3 => $var2
> };
> If $var is undefined, then the value of 'element_2' becomes 
> 'element_3'. Not what I want.
That doesn't ever happen with scalar values, defined or not. This 
normally occurs when a function returns nothing (e.g. "return" as 
opposed to "return undef"). Any functions called within hash 
construction are in list context, so if they return lists, they get 
incorporated into the hash. The simplest way to fix that is to 
explicitly set scalar context:

my $hash = { element_x => scalar function() };

or call the function first in scalar context and add it to the hash after:

my $var = function();
my $hash = { element_x => $var };


More information about the london.pm mailing list