Passing Array Reference to Subroutine

Summary: in this tutorial, you will learn how to pass array references to a subroutine. We will also show you how to define the subroutine that returns an array.

Before going forward with this tutorial, we recommend that you review the Perl reference if you are not familiar with the reference concept in Perl.

Passing an array to a subroutine

Let’s take a look at the following example:

#!/usr/bin/perl use warnings; use strict; my @a = (1,3,2,6,8,4,9); my $m = &max(\@a); print "The max of @a is $m\n"; sub max{ my $aref = $_[0]; my $k = $aref->[0]; for(@$aref){ $k = $_ if($k < $_); } return $k; }
Code language: Perl (perl)
The max of 1 3 2 6 8 4 9 is 9
Code language: Perl (perl)

In the program above:

  • First, we defined an array of integers @a.
  • Next, we passed a reference to the array @a to the subroutine &max, specified by \@a. For more information on array reference, please check it out array references tutorial.
  • Then, inside the subroutine &max, we defined a lexical variable $aref and set its values to the array reference stored in the argument array @_.
  • After that, we iterated over array elements via the lexical reference to find the maximum element.
  • Finally, we returned the maximum value as a scalar.

Returning an array from a subroutine

By applying the same technique, you can also pass multiple arrays to a subroutine and return an array from the subroutine. See the following example:

#!/usr/bin/perl use warnings; use strict; my @a = (1,3,2,6,7); my @b = (8,4,9); my @c = pops(\@a,\@b); print("@c \n"); # 7, 9 sub pops{     my @ret = ();     for my $aref(@_){         push(@ret, pop @$aref);     }     return @ret; }
Code language: Perl (perl)
7 9
Code language: Perl (perl)

How it works.

  • First, in the subroutine  &pops, we declared an empty array for storing elements that we removed from input arrays.
  • Next, we looped over the  @_ array to get the corresponding array argument, used the  pop() function to remove the last element of each array, and pushed it to the lexical array @ret.
  • Then, we returned the lexical array @ret.
  • After that, we called the subroutine  &pops and passed two array references:  \@a and \@b.
  • Finally, we returned an array from the subroutine and displayed its elements. The program displayed the last values of both @a and @b, which is 7 and 9.

If you want to pass a hash reference to a subroutine, the same technique is applied. You can try it as your homework to get familiar with passing references to subroutines.

In this tutorial, we have shown you how to pass arrays to the subroutine by using references and also guide you how to define subroutines that return arrays.

Was this tutorial helpful ?