in reply to Returning two lists from a sub

First you need to remember the "limits" of perl:

As found at perlsub optionally specifying the returned value, which will be evaluated in the appropriate context (list, scalar, or void) depending on the context of the subroutine call. If you specify no return value, the subroutine returns an empty list in list context, the undefined value in scalar context, or nothing in void context. If you return one or more aggregates (arrays and hashes), these will be flattened together into one large indistinguishable list.

This is not as "limiting" as one might expect.

There are several ways of passing back. You are fundamentally limited to returning values (1) as a return value or (2) via changed parameters to the sub. (Ok a third way is via a out of bounds global thingy.)

Within both of these, there are several ways to do it, and the "best" is really context dependent.

If you are looking for a return value, you could return a scalar, which is a array ref which has array ref elements to each of your lists, or you can return a list, which has array ref elements to each of your lists.

Whether you use 1 or 2 as your mechanism should really depend upon how you want the rest of your functions to appear. If you're modifying existing code, which technique is domoniate - use that.

Tis good to remember that this provides far greater functionality than the simple c-language return value :)

..Otto

Replies are listed 'Best First'.
Re^2: Returning two lists from a sub
by Anonymous Monk on Jun 07, 2007 at 17:38 UTC
    Why do you need a return value? Is there a specific reason you can't do this? my (@a, @b); &get_lists; print join(" ",@a),"\n",join(" ",@b); sub get_lists{ my @a = (1,2,3); my @b = (4,5,6); }

      ...other than the fact that it does not work...

      Your my in the sub hides the "outer" @a and @b.

      I did mention your technique as (Ok a third way is via a out of bounds global thingy.)