3

I have this code in Perl:

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

print f;

The function f returns reference to array, how can I convert returned value to array without additional variable, like here?

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

$a = f;
print @$a;

2 Answers 2

10

Are you just trying to do this?

print @{ f() };

You can dereference anything that returns a reference. It doesn't have to be a variable. It can even be a lot of code:

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

Perl v5.20 adds an experimental post dereference:

print f()->@*
Sign up to request clarification or add additional context in comments.

Comments

2

You could rewrite the subroutine 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 );

Note: this is how Perl6 subroutines would handle scalar/list contexts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.