12.1.3 Specifying the Number and Type of “Formal Parameters”

12.1.3  Specifying the Number and Type of “Formal Parameters”

   As we know by now, Perl does not allow us to write a function with a specified set of “formal parameters” like most other programming languages do. However, through a facility called prototypes, Perl allows one to state the number of individual scalar parameters sent to a subprogram and their types.

Suppose we want to rewrite our subprogram divide so that we make the types of the two “formal parameters” sent clear. We require that we send two scalars as parameters.

 Program 12.3

use strict;

#The function divide specifies the types of parameters it needs.
#The function takes two parameters each of which is a scalar
sub divide ($$) {
    my $result;
    my ($num, $denom) = @_;
    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);
divide (100, 20);
#divide (100);         #Error because not enough parameters are provided
#divide (100, 20, 3);  #Error because too many parameters are provided

 

That the function divide needs two scalar parameters is mandated by the presence of ($$) in the first line of the subprogram definition.

 

sub divide ($$)

 

The first $ sign tells us that the first parameter must be a scalar. This is because in Perl, all scalar variable names start with the $ sign. Similarly, the second parameter is also specified to be a scalar. That is, when we call the subprogram divide, we must pass two scalars as “formal parameters.” We cannot pass fewer than two or more than two “actual parameters.” If we do so, we get a compiler error. If we do not have the parameter types specified in the definition of the function, we would have been able to call with zero to any number of “actual parameters.” All the parameters would have been passed as an undifferentiated list.

As we know by now, unlike most programming languages, Perl still does not allow us to write subprograms with a list of formal parameters. But, it is quite likely that a future version of Perl will provide this facility. The ability to provide a list of “formal parameter” types is a first step towards doing so.