views:

191

answers:

2

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;
+9  A: 

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 };
brian d foy
yes :) first example exactly what I want
rsk
It took me a while to figure this out too...
Ryan Fox
+2  A: 

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

Brad Gilbert