[sf-perl] Return from a function

Quinn Weaver quinn at fairpath.com
Thu Feb 28 11:28:48 PST 2008

On Thu, Feb 28, 2008 at 11:15:40AM -0800, nheller at silcon.com wrote:
> I have an idea in my head that's obviously incorrect.
> Maybe its a mental block but I can't even think of where to look for an
> answer.  If the answer is obvious could y'all just say it but I would
> appreciate getting a keyword or referrence topic for my use later.
> [question]
> I was always under the assumption that Perl (like C) returns a single
> value from a function.  I seems like this is not true as it looks like the
> following function returns 3 values.  How could this be?
> my ($a, $b, $c);
> my ($paramA, $paramB);

Hi, Neil,

Good observation.  In fact, Perl _can_ return multiple values.  They come
back to the caller in a list.  So something like this is possible:

sub parse_tuple {
    my ($text) = @_;
    return ($variable_name, $value, $separator);

my ($var, $val, $sep) = parse_tuple('name=Neil');
# or...
my @results = parse_tuple('name=Neil');

Another way to achieve the same thing is to return a reference to an array.
This is more the C style of doing things.  That code would look like this:

sub parse_tuple {
    my ($text) = @_;
    my @retval = ($variable_name, $value, $separator);
    return \@retval;
    # More compact variants are possible, but they may be hard to read.

my $results_array_ref = parse_tuple('name=Neil');
my @results_array = @$results_array_ref;
my ($var, $val, $sep) = @results_array;
# Again, more compact variants are possible, but they may be hard to read.

Overall, the first method (with actual lists, not references) is easier to
code and read, and the performance difference is miniscule.  So this is one
place where Perl makes your life easier than C, IMO.

Quinn Weaver, independent contractor  |  President, San Francisco Perl Mongers
http://fairpath.com/quinn/resume/     |  http://sf.pm.org/

More information about the SanFrancisco-pm mailing list