rpg
rpg

Reputation: 1652

understanding this map behavior

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.

Upvotes: 5

Views: 344

Answers (2)

Protostome
Protostome

Reputation: 6029

map { (defined $_) && $_->[0] }

actually iterates through each and every element in the array, and apply some function or expression. in out case it is the following function: defined($_) && $_->[0] if your cell is undef the third cell in your array evaluates to defined(undef) && $->[0] ( which equals '' you can try it..), while the other evaluates to 1 && $->[0] which equals $->[0].

BTW, thats also the reason your second statement works, for each cell of your array, you choose the first inner cell.

Upvotes: 0

Brad Mace
Brad Mace

Reputation: 27886

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.

Upvotes: 4

Related Questions