Reputation: 16115
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
Upvotes: 16
Views: 314
Reputation: 9306
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
Upvotes: 19