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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With