returning

How do I return multiple variables from a subroutine?

The problem

Often you’ll want to return more than one variable from a subroutine. You could do this by returning all the values in an array, or by accepting variable references as parameters and modifying those.

In Perl however, you can return multiple variables easily.

Getting one variable back:

The output you should see is:

Getting two variables back:

The output you should see is:

You can of course return more than two variables. Just follow the syntax above and add more variables.

Returning two arrays

While this works fine for scalar variables. When you start playing with arrays and hashes you need to be careful.

For example, the following code may not quite do what you would think:

The output of this program is:

All of the data has been put into the first array! This is because all of the values are returned in a single big array, and then perl doesn’t know how to put that into two arrays, so it puts it all in the first one.

For this example to work properly, you’d need to return array references:

This has the output that you would expect:

In this case two references are returned into two scalar variables, so perl can work it out perfectly.

Often it is better to return references than arrays (or hashes) anyway. Imagine if you have a very large array. Returning it directly means that an entire copy of the array is made into another part of memory. However, if you return a reference to the array, the hugh array stays where it is and a reference to the array is copied around. Much better memory usage.

Returning two hashes

Hashes have the same problem. We won’t go into it in detail here but a hash can very easily turn into an array:

Would give the following output:

So if you were to return two hashes from a subroutine, like with arrays, all the data would end up in the first hash:

This has the following output:

Like arrays, use references instead:

Output is:

Just like arrays, returning references rather than the actual hash is much better memory usage.

Scroll to Top