1.10.1 A Subroutine with no Parameters
The following is a simple subroutine in Perl that has no parameters.
Program 1.16
#file subhello.pl
use strict;
my $name;
$name = "Brian";
hello ();
#########################
#Main program ends
#A subroutine that says hello.
sub hello{
#note that $name is variable that is global in the whole program
print "Hello! How are you doing $name?\n";
}
A subroutine can be defined anywhere in the program. Some prefer to have all subroutine definitions at the top of the program, others at the very bottom. Here, we define subroutines at the bottom of the program.
The program has two distinct parts. Informally, we call the upper part of the program above the subroutine definition, the main program. The second part follows, and in this part, we have defined the subroutine. If we had several subroutines, we can define them one after the other. The order of the main program and subroutine(s) can be reversed. It is usually not a good idea to intersperse subroutine definitions and statements of the main program.
The main program declares a variable called $name available everywhere within the program. The variable is assigned a value Brian. The next statement is hello (). This statement calls or invokes the subroutine.
The main program is separated from the subroutine using comment lines. A subroutine definition starts with the special word or keyword sub. It is followed by its block of statements included inside curly braces. The name of the subroutine becomes associated with its block of statements. The statements can be executed in the main program or inside another (or, even the same) subroutine by using the name of the subroutine. This is referred to as calling or invoking the subroutine.
The subroutine hello is called in the main program, and it has access to the value of the variable $name within it.
If the program is stored in the file subhello.pl, it can be run by typing its names on the command-line argument.
%subhello.pl
The output of the program is given below.
Hello! How are you doing Brian?
The execution of the last statement in the main program calls the subroutine hello.
Note that a subroutine is not executed if it is not called. Thus, it is possible that there is a subroutine definition in the body of a program, and the subroutine is useless in the sense that it is not called. Having such subroutines is not a good practice, but in large programs, it can happen as the program evolves.
The subroutine hello given above does not have any parameters. This is clear because the parentheses pair next to the subroutineĆs name in the call does not enclose anything. Use of a parameter allows us to make slightly different calls to the same subroutine. We see this in the next section.
