Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in some programming languages, these are considered different. The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier. One can avoid using the return statement.
Defining Subroutines: The general form of defining the subroutine in Perl is as follows-
# body of method or subroutine
Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as follows-
The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before Perl 5.0 there was another way of calling the subroutine but it is not recommended to use because it bypasses the subroutine prototypes.
Passing parameters to subroutines: This is used to pass the values as arguments.This is done using special list array variables ‘$_’. This will assigned to the functions as $_, $_ and so on.
Advantage of using subroutines:
- It helps us to reuse the code and makes the process of finding error and debug easy.
- It helps in organizing the code in structural format.Chunks of code is organized in sectional format.
- It increases the code readability.