How to Return Multiple Values From a Subroutine in Perl

How to Return Multiple Values From a Subroutine in Perl


Perl is a language useful for scripting, file processing, and other forms of development. Subroutines can return a single variable only. To return more, they can be manipulated, then returned for further use.


A Perl interpreter (should be default on Linux, distributions such as ActiveState can be used for Windows).


Set up your text file (with file extension .pl) as follows, starting from the first line:
use strict;
use warnings;
my $data1;
my $data2;
my $data3;
my $data4;

The first line indicates where the Perl interpreter is located. This may be irrelevant on Windows, but whether it is included or not, the location will be used on Linux. The next lines signal what mode to run in. Strict mode with warnings will throw errors and display warnings if present. The last four lines are declaring variables to store values that will be returned from a subroutine and used later.

sub sub1{
my @values;
my $valuesRef;
$data1= 1;
$data2= 2;
$data3= 3;
$data4= 4;
push @values, $data1;
push @values, $data2;
push @values, $data3;
push @values, $data4;
$valuesRef = \@values;
return $valuesRef;

Next, perhaps a few lines down from the first lines of the file, we create a subroutine sub1. We then make two new declarations, and initialize values into the previously declared variables. We create an @values array, and pass the values into the array by push’ing. Then, we pass a reference of the @values array into a valuesRef reference scalar. Then, we return this reference, which we can access later to gain the address of the previously populated array.

my $valuesRef;
my @values;
$valuesRef = sub1();
Once the sub1 subroutine has been defined, we can re-access the contained array. To do this, we grab the returned reference and put it in a new scalar. The array then can be redefined by:
@values = @{$valuesRef};