Passing Array Reference to Subroutine (original) (raw)

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.

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=aref = aref=_[0]; my k=k = k=aref->[0];

for(@$aref){
    <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">k = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal" style="margin-right:0.03148em;">k</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>_ if($k < $_);
}
return $k;

}`Code language: Perl (perl)

The max of 1 3 2 6 8 4 9 is 9Code language: Perl (perl)

In the program above:

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 9Code language: Perl (perl)

How it works.

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 on how to define subroutines that return arrays.

Was this tutorial helpful ?