Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding this map behavior

Tags:

perl

I am using map to extract the first element of a 2D array. Here is the small code snippet.

my $array = [ [1,11,111], [2,22], undef, [4] ];

my @firstList = map { (defined $_) && $_->[0] } @$array;

So here I am expecting the map to return an array having elements with value either undef or first element of $array's element.

but the output is not same what I am expecting. For undef, I am getting element of type 'scalar'.

If I change the map statement with following block, then I am getting expected result.

my @firstList = map { $_->[0] } @$array;

Please help me to understand about these two map statements.

like image 786
rpg Avatar asked Oct 10 '22 15:10

rpg


1 Answers

They both return the result of the last operation performed.

For the first, when it evaluates (defined $_) && $_->[0] for undef, it sees that defined $_ is false and stops processing the boolean expression. $_->[0] isn't evaluated at all in this case. defined $_ was the last operation evaluated, and its result was false, which I'm guessing is represented with a 0.

For the second, it's the actual value from the child of @$array which is where it's getting the undef value.

like image 70
Brad Mace Avatar answered Oct 26 '22 23:10

Brad Mace