Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map() mask the 'undefined value' error?

Tags:

perl

I'm wondering why a call to map in the second snippet makes the 'undefined value' error gone?

use strict;
use warnings;
my $x;
my @a = @{ $x }; # error: Can't use an undefined value as an ARRAY reference

Compare to:

use strict;
use warnings;
my $x;
my @a = map $_, @{ $x }; # no error, @a is empty
like image 314
planetp Avatar asked Oct 25 '16 18:10

planetp


People also ask

Why does .map return undefined?

The map() method returns undefined values when we forget to explicitly return a value in the callback function we passed to the method. Make sure to return a value from the callback function to not get any undefined values in the array.

What is map () in JavaScript?

Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

Does map () alter the array it is called upon?

map() method allows you to loop over every element in an array and modify or add to it and then return a different element to take that elements place. However . map() does not change the original array. It will always return a new array.

How do you fix undefined properties Cannot be read?

To resolve your TypeError: Cannot read properties of undefined (reading '0') , go through these steps: Ensure you are using the correct variable. Perform a simple check on your variable before using it to make sure it is not undefined. Create a default value for the variable to use if it does happen to be undefined.


1 Answers

This is due to the way that map() does aliasing (it's essentially using a for() loop). What's happening is that the aref is being used in l-value context, and therefore is being auto-vivified into existence.

In your former example, you're attempting to use the aref directly in r-value context, which is why it generates the error (because no auto-vivification happens).

You can simplify your test to use for(), and you'll get the same result as with map():

use warnings;
use strict;

my $x;

for (@{ $x }){
    print "$_\n";
}

...no output.

To visually see that $x was auto-vivified as an array reference, you can use the ref() function:

my $x;
my @a = map $_, @{ $x };

print ref $x;

Output:

ARRAY
like image 62
stevieb Avatar answered Oct 11 '22 04:10

stevieb