Perl Language Lists Return list from subroutine


Example

You can, of course, return lists from subs:

sub foo {
    my @list1 =  ( 1, 2, 3 );
    my @list2 =  ( 4, 5 );

    return    ( @list1, @list2 );
}

my @list =  foo();
print @list;          # 12345

But it is not the recommended way to do that unless you know what you are doing.

While this is OK when the result is in LIST context, in SCALAR context things are unclear. Let's take a look at the next line:

print scalar foo();  # 2

Why 2? What is going on?

  1. Because foo() evaluated in SCALAR context, this list ( @list1, @list2 ) also evaluated in SCALAR context
  2. In SCALAR context, LIST returns its last element. Here it is @list2
  3. Again in SCALAR context, array @list2 returns the number of its elements. Here it is 2.

In most cases the right strategy will return references to data structures.
So in our case we should do the following instead:

 return    ( \@list1, \@list2 );

Then the caller does something like this to receive the two returned arrayrefs:

 my ($list1, $list2) = foo(...);