Introduction to Subroutines

Let's introduce a subroutine, its types, and its syntax in this lesson.

What is a subroutine?

A subroutine is a block of code that is written in order to perform a specific task.

Let’s discuss a real-life example to understand the concept better. While using a vending machine, we put the money in the machine and select the desired item to be purchased. The machine gives back the requested product. To accomplish this task, there is a subroutine written at the backend.

Subroutines work in a similar way. They take the required information to perform a task as input parameter(s), perform the required operations on these parameters, and then return the final answer.

Types of subroutines

In Perl, there are two major types of subroutines:

  • Built-in subroutines
  • User-defined subroutines

Built-in subroutines

Perl provides some built-in subroutines that a user can use. These subroutines are predefined and just need to be called.

User-defined subroutines

Apart from built-in subroutines, Perl also allows us to make our own customized subroutines. These subroutines can be written so that they would perform the required task wherever necessary, once they’re called.

We need to declare the subroutine before calling from main. Otherwise, it will give a runtime error.

Implementation

Now, let’s discuss the method to write a user-defined subroutine below.

Example

Let’s take a look at an example now.

Press + to interact
sub Examplesubroutine { #subroutine that outputs some text
print "This is a user-defined subroutine";
}
# Calling the subroutine
Examplesubroutine();

Explanation

As we can see from the example above:

Line 1

  • First, write the keyword sub.
  • Next, write the name of the subroutine. In this case, it’s Examplesubroutine.

Line 2

  • Then, write the body of the subroutine in between the curly braces.

Line 6

  • In the end, call the subroutine, as seen in line 6 above.