12.1.1 Functions With No Parameters

12.1.1  Functions With No Parameters

  Sometimes we want to write a function that is very simple and has no formal parameter. Such a function can be used to print a message explaining an error that occurs again and again. The program is given below.

 Program 12.1

#!/usr/bin/perl
use strict;

#Defines a function that prints an error message on divide by zero.
sub printError {
    print "You are trying to divide by zero.\n"
    }

####main program
my ($num, $denom, $result); 

#first division
$num = 100; $denom = 10;
if ($denom == 0) {printError;}
else {
    $result = $num/$denom;
    print "$num/$denom = $result\n";
};

#second division
$num = 100; $denom = 0;
if ($denom == 0) {printError;}
else {
    $result = $num/$denom;
    print "$num/$denom = $result\n";
};

 

The program contains a function definition. The function is called printError. To define a function, we use the keyword sub and follow it by the name of the subprogram and then the code of the subprogram in a block. The function takes no parameter. It simply prints a sentence saying that the program is attempting to divide by zero. Division by zero is not possible and results in an error. The program is invoked twice in the main program. Before dividing $num by $denom, the program checks to see that $denom is equal to zero. If it is equal to zero, it prints an error message. Otherwise, it prints the result of the division.

Since we use use strict, the variables used in the main program as well as in the function must be declared prior to their use. The function body does not have any variables. The three variables used in the main program are declared before they are used. The function can be defined anywhere in the program, not at the beginning as we have done. However, it is good practice to define all subprograms before they are used. Also, it is a good practice to put all function definitions together and not intersperse them throughout the main program’s text.