Perl subroutine - how to return multiple values

Perl subroutines - multiple return values FAQ: Can you share some examples of how to return multiple values from a Perl subroutine?

Did you know that you can return multiple values from a Perl subroutine (function)? As a practical matter I haven't used this feature very much, but I've always thought it was an interesting programming language feature, very different from many other languages.

A simple Perl subroutine to return multiple values

As a quick demonstration of this unique Perl sub (subroutine) feature, here's a simple Perl function named foo that returns two strings:

# a perl subroutine that returns two strings
sub foo
{
  return 'foo', 'bar';
}

As you can see, in a simple case like this, to return multiples values from a Perl subroutine, just separate the values with a comma when using the Perl return operator.

Calling a Perl subroutine that returns multiple values

When you call a Perl subroutine that returns multiple values, you just need to use a syntax like this:

($a, $b) = foo;

This assigns the returned values to my Perl variables $a and $b.

To demonstrate this, if I create a complete Perl script like this:

sub foo
{
  return 'foo', 'bar';
}

($a, $b) = foo;

print "a = $a\n";
print "b = $b\n";

and then run this script, the output will look like this:

a = foo
b = bar

I think that's pretty cool, and a little bit of a mind-stretcher. You can more or less accomplish the same thing in a language like Java by returning a List, Collection, or other data type that lets you store multiple elements, but you can't simply return two strings, as I've shown here.

More Perl subroutine (sub) information

I hope these examples of how to return multiple values from a Perl subroutine have been helpful.

For more Perl sub (subroutine, or function) information, I just created a Perl subroutine (sub) tutorial, and I'll also be adding other Perl subroutine tutorials here over time.

Post new comment

The content of this field is kept private and will not be shown publicly.