Why does the map return an empty array?

I have a problem in Perl, I do not understand. I split it into this very short code.

Why does the Perl function return an empty array? Shouldn't an array with 9 s be returned ? mapundef

sub mySub{
    return;
}

my @arr = (1 .. 9);
my @arr2 = map( mySub($_), @arr );

print @arr . ' ' . @arr2, "\n";

He prints "9 0".

This is probably something simple, but it perldocdoes not help.

+3
source share
3 answers

A more general answer to your question is this: when returnused without an argument, the return value depends on the calling context:

list context    returns an empty list
scalar context  returns an undefined value

For example:

use strict;
use warnings;
use Data::Dumper;

my (@list);
sub mySub { return }
@list = map(       mySub($_), 1..2); print Dumper(\@list);
@list = map(scalar mySub($_), 1..2); print Dumper(\@list);

Output:

$VAR1 = [];
$VAR1 = [
          undef,
          undef
        ];
+8
source

, undef, . 9 , - .

undef, .

+7

try it

use strict;
use warnings;

sub mySub{
    return undef;
}

my @arr = (1,2,3,4,5,6,7,8,9);
my @arr2 = map(&mySub, @arr);

print @arr." ".@arr2;

If you need to get a list containing undefs, you need to explicitly specify undef. The fact is that the map calls your mySub in the context of the array (check what exactly you want to get from this unit). return statement essentially returns an empty list every time you call sub, which results in an empty array as a whole

+3
source

Source: https://habr.com/ru/post/1713179/


All Articles