Perl Subroutine
Perl Basics – Part 12
Perl Course
Foreword: Now, a Function is a set of statements that perform a specific task. In this tutorial I explain the basics of Perl user-defined subroutines.
By: Chrysanthus Date Published: 29 Mar 2015
Introduction
You should have seen some functions before. An example of a function you have seen, is the print function. The functions you have seen so far are functions that are predefined in the Perl Interpreter. You can write your own function to do what you want. Such functions are called user-defined functions. In Perl, a function is called a subroutine. In this tutorial I explain the basics of Perl user-defined subroutines.
You should have read the previous parts of the series before reaching here, as this is a continuation.
Defining Subroutines
The group of statements to perform a particular task forms the subroutine, however you need to group them in a particular way. By doing this, we say you are defining a subroutine in Perl. This process can actually be split into two. One phase is called, declaring the subroutine and another phase is called, defining the subroutine. For this tutorial and for basic Perl programming, we shall use a single process, which is defining the subroutine.
A subroutine definition consists of the following in the order given
- The reserved word, sub.
- The name of the subroutine.
- The statements that define the subroutine, enclosed in curly braces. The statements in a subroutine can have among them calls to other subroutines defined in the current program (application).
Note: another name for reserved word is keyword.
In the following example, we define a subroutine that will add two numbers, find the square of the sum and then return the result.
sub mySub
{
my $num1 = 2;
my $num2 = 3;
my $sum = $num1 + $num2;
my $square = $sum * $sum;
return $square;
}
The subroutine begins with the reserved word, sub. The name of the subroutine is mySub. This is followed by parentheses. Then you have the block, delimited by { and }. In the block, you have the declaration and assignment of the two numbers. The third statement in the block sums the two numbers. The fourth statement squares the sum. The last statement returns the square to the statement that would call the subroutine, outside the subroutine. The reserved word, return, is used for this. It is followed by a variable or a literal. Not all subroutines end with the return instruction (statement). Some subroutines just perform a task and do not return anything.
Calling a Subroutine
You call a subroutine by just typing the name of the subroutine, optionally followed by parentheses, in a statement. The following code illustrates this. Try it:
use strict;
sub mySub
{
my $num1 = 2;
my $num2 = 3;
my $sum = $num1 + $num2;
my $square = $sum * $sum;
return $square;
}
my $result = mySub();
print $result;
This code is similar to the previous with the addition of the two last statements. The last-but-one statement calls the subroutine. This statement call is outside the subroutine. The right operand of the statement is “mySub()”. It is this expression that calls the subroutine. When it calls the subroutine, it receives the value returned by the return statement in the subroutine. This value is now assigned to the variable, $result. The last statement displays the result.
A subroutine call does not always have to assign a return value to a variable. Subroutines that do not have return values are called by just typing the name, followed by parentheses (then semicolon, to form a statement).
The last-but-one statement in the code is:
my $result = mySub();
mySub() is the function call. In Perl, the parentheses are optional. You can call a function without typing the parentheses. However, it is good practice to type them, as this is required in other languages; a programmer knows more than one computer language. Also, you can have space between the function name and the parentheses; the space is optional.
Now, in the above subroutine we can only deal with two particular numbers, which are 2 and 3. This is a disadvantage. If we declare (create) and assign the variables outside the subroutine, then we can always change the values of the variables, then send the variables to the subroutine before the subroutine is executed. In this way, we shall be able to deal with many other pairs of numbers. The following example illustrates this:
use strict;
my $num1 = 4;
my $num2 = 5;
sub mySub
{
my $sum = $_[0] + $_[1];
my $square = $sum * $sum;
return $square;
}
my $result = mySub($num1, $num2);
print $result;
Try the above code (the explanation follows). This time the variables have been declared and assigned outside the subroutine. Some other subroutine elsewhere in the code can actually change these values. However, a subroutine cannot change the value of a variable inside some other subroutine (everything being equal).
In the last-but-one statement, where the subroutine is called; the parentheses have two variables. These variables in this position are called Arguments. These arguments of the subroutine are the variables declared outside the subroutine. The arguments to a subroutine call, can also be literals, something like:
my $result = mySub(4, 5);
Any subroutine definition block, has an array called, @_ . The name of the array is _ ; it is preceded by @ since it is an array. This array is not seen by you the programmer, but you can use it. As soon as the execution of the subroutine (block) starts, the arguments sent to the subroutine become the elements of this array, in the order sent. In the above code, the argument, $num1 which is 4, becomes the value of $_[0]. The other argument, $num2, which is 5 becomes the value of $_[1]. This explains the first statement in the sub routine block above. Read the code again.
We have been using the print function, passing only one argument each time we called it. You can actually pass more than one argument. Separate the arguments with commas as in the following code:
use strict;
print ("one", "\n", "two", "\n", "three");
Try the above code. There are actually five arguments in the list. Each of the arguments is a literal. Do not forget that the parentheses are optional for the print and other predefined functions, as well as for the ones you define.
Hey, you can use variables in place of the literals.
Let us stop here and continue in the next part.
Chrys
Related Links
Perl BasicsPerl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course
BACK NEXT