How to convert function return value from array reference?

I have this code in Perl:

sub f {
    return [1,2,3]
}

print f;

The function freturns an array reference, how can I convert the return value to an array without an additional variable, for example here?

sub f {
    return [1,2,3]
}

$a = f;
print @$a;
+3
source share
2 answers

Are you just trying to do this?

print @{ f() };

You can dereference anything that returns a link. It does not have to be a variable. It could even be a lot of code:

print @{ @a = grep { $_ % 2 } 0 .. 10; \@a };

Perl v5.20 adds the difference between experiments :

print f()->@*
+10
source

You can rewrite a routine to return different things in different contexts.

sub f {
  my @return = 1..3;

  return  @return if wantarray;
  return \@return;
  # if you want to return a copy of an array:
  # return [@return];
}

say f;        #   list context => wantarray == 1
say scalar f; # scalar context => wantarray == 0
f();          #   void context => wantarray == undef
123
ARRAY (0x9238880)
my $a_s  = f; # scalar
my($a_l) = f; # list

my @b_l  =        f; # list
my @b_s  = scalar f; # scalar

my %c_l  =        f; # list
my %c_s  = scalar f; # scalar

$a_s ==   [ 1..3 ];
$a_l ==     1;

@b_l == (   1..3   );
@b_s == ( [ 1..3 ] );

%c_l == ( 1 => 2, 3 => undef );
%c_s == ( ARRAY(0x9238880) => undef );

: Perl6 /

+2

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


All Articles