next up previous contents
Next: Sorting Up: Programming in Perl Previous: Associative arrays   Contents

Writing functions

A function in Perl begins with the keyword sub followed by a name. The interesting feature of functions in Perl is that there is no explicit declaration of the list of arguments to the function. When a function is invoked, the list of arguments, if any, is made available to the function in a specially named list, @_. The function can then shift through @_ to extract all the values that are passed to it.

For instance, here is a function that returns the maximum of exactly two values:

  sub max {
   my ($a,$b,@rest) = @_;     # Get first arguments from @_ in $a, $b
   if ($a > $b) {return $a};
   return $b;
  }

This function does not check whether @_ does in fact have two valid values. No matching is done while invoking a function, since there is no template associated with a function. Thus, the function max defined above could be invoked, legally, as max(), or max(1) or max($x,$y) or max(@list) or .... Here is a more generic version of max, that works ``properly'' provided it has at least one argument. Recall that for an array @list, the value @list in scalar context gives the length of the array.

  sub max {
   my ($tmp);                    # Declare $tmp as a local variable
 
   unless (@_) return 0;         # Return 0 if input list is empty

   my $max = shift @_;           # Set $max to first value in @_
   while (@_){                   # Compare $max to each element in @_
     $tmp = shift @_;
     if ($tmp > $max){$max = $tmp;}
   }
   return $max;
  }


next up previous contents
Next: Sorting Up: Programming in Perl Previous: Associative arrays   Contents
Madhavan Mukund 2004-04-29