Perl subroutine values - How to return multiple values from a Perl function

Perl subroutine FAQ: How do I return multiple values from a Perl subroutine (Perl function)?

One of the things I really like about Perl is that you can return multiple values from a function (and you don't have to create some type of artificial class to encapsulate them). Here's the basic way to return multiple values from a function/subroutine named foo:

sub foo {
  return ('aaa', 'bbb', 'ccc');
}

($a, $b, $c) = &foo();

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

As you can see from the assignment statement above, you can return these multiple values into three separate variables, $a, $b, $c, which is also very cool.

If you save this Perl code to a file and then run it you'll get this output:

a = aaa, b = bbb, c = ccc

As you can see from the output, the three values I return from the function are assigned to my three variables when I call the function.

Returning multiple values to an array

You can also assign an array to hold the multiple return values from a Perl function. You do that like this:

sub foo {
  return ('aaa', 'bbb', 'ccc');
}

(@arr) = &foo();

print "@arr\n";

As you can see, most of the code is the same, except I now assign an array (@arr) to contain the three return values from my function.

Save this Perl code to a file and run it and you'll see this output:

aaa bbb ccc

As you can see from these examples, you can assign multiple return values from a Perl function either to separate variables, or a single array.