Subroutines and Parameter Passing in Perl

Tom Kelliher, CS 318

Jan. 28, 2000



Mini-quiz on readings.

A syllabus!


Read Chs. 1--5.

From Last Time

Reverse-engineering a JavaScript program.


  1. Subroutines.

  2. Example.

  3. Exercise.

Coming Up

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


  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?


#!/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;


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/

Thomas P. Kelliher
Thu Jan 27 19:38:12 EST 2000
Tom Kelliher