Prerequisite: Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language, the user wants to reuse the code. So the user puts the section of code in a function or subroutine so that there will be no need to rewrite the same code again and again. For this reason, function or subroutine is used in every programming language. These functions or subroutines can take various different types of data structures as parameters. Some of these are explained below:
- Passing Lists or Arrays to a Subroutine
- Passing References to a Subroutine
- Passing Hashes to a Subroutine
- Passing File Handles to a Subroutine
Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a parameter and an array variable @_ is used to accept the list value inside of the subroutine or function.
Example 1: Here a single list is passed to the subroutine and their elements are displayed.
Given list is 1 2 3 4
Example 2: Here two lists are passed to the subroutine and their elements are displayed.
Given lists' elements are 1 2 3 4 10 20 30 40
Example 3: Here a scalar argument and list is passed to the subroutine and their elements are displayed.
List and scalar elements are 1 2 3 4 100
Passing References to a Subroutine: References can also be passed to the subroutines as a parameter. Here the reference of the given array is passed to the subroutine and the maximum value of array elements is returned.
The max of 10 20 30 40 50 is 50
Passing Hash to a Subroutine: A Hash can also be passed to a subroutine as a parameter and its key-value pair is displayed.
Company : GeeksforGeeks Location : Noida
Passing File Handles to a Subroutine: For creating a file or accessing the file contents one needs a filehandle which is nothing but a structure which is used along with the operators to access the file in a certain mode like reading, writing, appending, etc. FileHandles can also be passed to a subroutine as a parameter to perform various operations on Files.
In the below example, a filehandle is passed to a subroutine:-
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.