12.1.4 Optional Parameters

12.1.4  Optional Parameters

 Perl also allows us to write functions that take optional parameters. In Perl, we can state some parameters to be required parameters and some more to be to optional parameters. This is to some extent like Common LISP that allows us to write functions that take optional parameters. The following program shows this facility.

 Program 12.4

use strict;

#Both the first parameter and the second parameter must be scalars.
#the second parameter is optional
sub divide ($;$) 
{
    my $result;
    my ($num, $denom) = @_;
    unless (defined ($denom)){
            $denom = 1;
    }
    if ($denom == 0){
        print "You are trying to divide by zero: $num/$denom.\n";
    }
    else {
         $result = $num/$denom;
         print "$num/$denom = $result\n";
    }
}

#main program
my ($num, $denom); 
$num = 100; $denom = 10;
divide ($num, $denom);
divide ($num, 0);

#The next call defaults the denominator to 1 because it is not provided.
divide $num;

 

In this program, we write a subprogram called divide that requires one scalar “actual parameter,” and may have a second scalar “actual parameter” that is optional. This is done by stating so right after the name of the subprogram when we state the types of the parameters for the subprogram. Here, the first line of the subprogram definition looks like the following.

 

sub divide ($;$)

 

In specifying the types of the function’s “formal parameters,” we separate the types of the required “formal parameters” from the types of the optional “formal parameters” by a semicolon. In this specific case, the types of the parameters are specified using $;$. This means that one scalar parameter is necessary and the second scalar parameter is optional.

In the body of the subprogram, there is a conditional unless statement whose condition is given as the following.

 

(defined ($denom))

 

This checks to see if in a call to divide, a value has been provided for the second parameter. If a value has not been provided in the call, the value of the parameter inside the subprogram is undefined. If the value is undefined, the defined function returns true. In such a case, the value of $denom is defaulted to 1. Towards the end of the main program, we have a call to divide that looks like the following.

 

divide $num;

 

In this call, the value of the second parameter will default to 1.