Subroutines and Parameter Passing in Perl

Tom Kelliher, CS 318

Feb. 2, 2000

Administrivia

Announcements

Mini-quiz on readings.

Assignment

Read Chs. 1--5. Will provide a study sheet on home page.

From Last Time

Firewalls and DNS.

Outline

  1. Subroutines.

  2. Example.

  3. Exercise.

Coming Up

Packets and frames (Ch. 6). A Perl assignment.

Subroutines

  1. The declaration.

  2. The definition.

  3. Calling a subroutine.

Parameter Passing

  1. @ARGV list.

  2. @_ list.

  3. How do we know how many items in a list???

Return Values

  1. How?

  2. Can we return a list?

  3. Return into what?

Example

#!/usr/local/bin/perl -w

# A somewhat silly program, demonstrating the use of lists to pass
# parameters.  Also demonstrates a subroutine returning a value.
#
# The program adds the numbers given as command line arguments.  The
# arguments are passed via the list @ARGV.  Note that parameters passed
# to a subroutine are passed via the list @_.


use strict;


# Prototype

sub add;


# main

{
   my $sum;
   my $count = $#ARGV + 1;

   $sum = add(@ARGV);

   print "\nThe sum of your $count numbers is $sum.\n";

   exit 0;
}


# Adds the numbers in the list passed in and returns the sum.

sub add
{
   my $i;
   my $last = $#_;
   my $sum = 0;

   for ($i = 0; $i <= $last; ++$i)
   {
      $sum += $_[$i];
   }

   return $sum;
}

Exercise

Working in groups of two, modify the Perl program to print the minimum and maximum of the command line arguments. You can find the program on the class home page or in phoenix:~kelliher/pub/cs318/add.pl.



Thomas P. Kelliher
Wed Feb 2 08:34:12 EST 2000
Tom Kelliher