melguin has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a subroutine in a module that returns a list after rummaging through a DB. At first I was going to return a reference, then when I started looking what I had done before, it seems that I've been returning a mix of references and arrays.

It seems to me that it would be easier on the end user to have it return an array, but if the list gets really big a reference might be better.

When is it best to return an array, and when is it better to return a reference to an array?

melguin.

  • Comment on Advantages to returning array vs. reference

Replies are listed 'Best First'.
Re: Advantages to returning array vs. reference
by pjf (Curate) on Oct 14, 2001 at 04:51 UTC
    Update: Fixed my link to previous discussions on the topic. Thanks to jptxs and Hopes for pointing out that I typoed on the link-id.

    For previous discussions on this topic, see here.

    In short, passing around references is much much faster, but can confuse people who are new to Perl, and may give your caller access to things they shouldn't if (say) you're passing back references to package variables.

    Provided you don't have these problems, you may want to use wantarray to figure out what the caller is expecting. If they want a scalar, give them a reference. If they want a list, then return an array:

    if (wantarray) { return @results; } else { return \@results; }
    This adds a bit more DWIM-ism to your code, although it also runs the risk of confusing some people if they're expecting to get the number of results if they're calling your function in a scalar context.

    Cheers,
    Paul

Re: Advantages to returning array vs. reference
by hopes (Friar) on Oct 14, 2001 at 18:18 UTC
    In add to pjf answer I want to point that if you want to return at least 2 lists (arrays or hashes) it's better to return references, because
    return (@a,@b)
    should push @a and @b in a list, and then return this list. It is not possible to separate them.

    It's better to code:
    return (\@a,\@b);
    and then receive the arrays as references
    ($ra,$rb)=myfunc();
    See perldoc perlref for more details
    I want to point also that returning a referece is faster and cheaper (in terms of CPU and memory), but better is not the best word we can use, it depends of the problem (See this node written by merlyn)

    Hope this help
    Hopes

    Thanks to graq for the information about the typo in my code