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.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy