Perl Subroutine

Summary: in this tutorial, you will learn about the Perl subroutine, which is also known as a function or user-defined function in Perl.

Introduction to Perl subroutine

Perl Subroutine

A subroutine is a block of code that can be reusable across programs. Perl subroutine is very flexible and powerful. You can define a subroutine anywhere in your program. If you have subroutines defined in another file, you can load them in your program by using the use, do or require statement.

A Perl subroutine can be generated at run-time by using the eval() function. You can call a subroutine directly or indirectly via a reference, a variable or an object.

Perl also allows you to create anonymous subroutines that can be accessible through references.

Perl subroutine syntax

To define a subroutine, you use the following syntax:

sub NAME  PROTOTYPES ATTRIBUTES BLOCKCode language: Perl (perl)

Let’s examine the syntax above in greater detail.

  • First, you use  sub keyword followed by the name of the subroutine. Because subroutine has its own namespace, you can have a subroutine named &foo and a scalar named $foo. We will explain the ampersand (&) in the subroutine name later.
  • Second, PROTOTYPES tells Perl what parameters the subroutine expects. The ATTRIBUTES gives subroutine additional semantics. Perl provides three standard attributes including locked, method and lvalue. Both ATTRIBUTES and PROTOTYPES are optional.
  • Third, the BLOCK is where you put the code.

The following example defines a simple subroutine that displays a message.

sub say_something{
     print "Hi, this is the first subroutine\n";
}Code language: Perl (perl)

To call a subroutine, you use the following syntax:

&subroutine_name;Code language: Perl (perl)

The ampersand ( &) prefix is a part of the subroutine name, however, it is optional when you call the subroutine. You can call a subroutine by specifying its name with parentheses as shown following:

subroutine_name();Code language: Perl (perl)

You can call the &say_something subroutine in any of the following forms:

&say_something;
say_something();Code language: Perl (perl)

In some cases, the ampersand ( &) is required, for example:

When you use a reference that refers to the subroutine name

$subref = \&subroutine_name;Code language: Perl (perl)

When you call subroutine indirectly by using one of the following syntaxes:

&$subref 
&{$subref}Code language: Perl (perl)

When you use the subroutine name as an argument of defined or undef function.

Perl subroutine parameters

It is more useful if we can pass parameters to a subroutine as the inputs and get something out of it. In Perl, all input parameters of a subroutine are stored in a special array @_. If you want to refer to the  nth argument, just use $_[n-1] syntax.

The following example demonstrates how to use argument lists in the subroutine:

#!/usr/bin/perl
use warnings;
use strict;

print &sum(1..10), "\n";

sub sum{
    my $total = 0;
    for my $i(@_){
        $total += $i;
    }
    return $total;
}Code language: Perl (perl)

First, we defined the &sum subroutine that calculates the sum of its arguments. In the subroutine, we looped over the elements of the  @_ array, added up their values and returned the result by using the return statement. Then, we passed an array of 10 integers (1..10) to the &sum subroutine and displayed the result.

The  @_ array is used as an alias of the arguments therefore if you make any changes to the elements of the @_ array, the corresponding argument changes as well. More information on how to pass parameters to a subroutine.

Noticed that when you pass an array or a hash to a subroutine, you actually pass all elements of the array or hash to it. To pass an array or a hash to a subroutine, you must pass a reference that refers to the array or hash.

Perl subroutine – returning values

Implicit returning value

A subroutine implicitly returns a value that is the result of the last expression in its body. Consider the following example:

#!/usr/bin/perl
use warnings;
use strict;

print &say_hi , "\n";
sub say_hi{
    my $name = 'Bob';
    print "Hi $name \n";
    $name;
}Code language: Perl (perl)

The last expression in the subroutine  &say_hi is  $name so it returns a string with the value Bob.

Explicit returning value with return statement

Another way to return a value inside the subroutine is to use the return statement explicitly. The following is another version of subroutine &say_hi with return statement:

sub say_hi{
    my $name = 'Bob';
    print "Hi $name \n";
    return $name;   
}Code language: Perl (perl)

You can use multiple return statements inside a subroutine. Whenever the return statement is reached, the rest of the subroutine is skipped and a value is returned.

Returning undef value

Sometimes, it is useful to return an undefined value undef from a subroutine so that we can distinguish between a failed call from one that returns false or no results.

For example, a subroutine may return an undefined value undef when a particular parameter is not supplied as the following example:

#!/usr/bin/perl
use warnings;
use strict;

my @a = ();
my $j = min(@a);

if(defined $j){
   print("Min of @a is $j \n");
}else{
   print("The array is empty.\n");
}

my @b = (100,12,31);
my $k = min(@b);

if(defined $k){
  print("Min of @b is $k \n");
}else{
   print("The array b is empty.\n");
}

sub min{
   my $m = shift;
   return undef unless defined $m;
   for (@_){
      $m = $_ if $m > $_;
   }
   return $m;
}Code language: Perl (perl)
The array is empty.
Min of 100 12 31 is 12

How it works.

  • First, we defined a subroutine  &min that returns the minimum element of an array. If the array is empty, the subroutine returns the undef value. In the main program, we passed the  @a array to the subroutine. Because  @a is an empty array so the returning value that is assigned to variable $j is undefined undef.
  • Second, we used the defined function to check if a variable is defined. In this case, it returned false so we displayed that the array  @a is empty.
  • Third, we passed an array  @b which contains 3 elements to the subroutine &min. In this case, we got the minimum value back which is 12.

In this tutorial, you’ve learned how to define a Perl subroutine and call it from the main program. You can start defining your own subroutines to get familiar before going to the next tutorial.

Was this tutorial helpful ?