Pregunta

Task: to build hash using map, where keys are the elements of the given array @a, and values are the first elements of the list returned by some function f($element_of_a):

my @a = (1, 2, 3);
my %h = map {$_ => (f($_))[0]} @a;

All the okay until f() returns an empty list (that's absolutely correct for f(), and in that case I'd like to assign undef). The error could be reproduced with the following code:

my %h = map {$_ => ()[0]} @a;

the error itself sounds like "Odd number of elements in hash assignment". When I rewrite the code such that:

my @a = (1, 2, 3);
my $s = ()[0];
my %h = map {$_ => $s} @a;

or

my @a = (1, 2, 3);
my %h = map {$_ => undef} @a;

Perl does not complain at all.

So how should I resolve this — get first elements of list returned by f(), when the returned list is empty?

Perl version is 5.12.3

Thanks.

No hay solución correcta

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top