CIW Course Revision Site

Perl - Introduction to Subroutines

In a Nutshell - CIW Course Section 2, Part B2, Chapter 4

 

Overview of Subroutines

Once you get past the basics of Perl programming you will find subroutines invaluable. These named blocks of code avoid repetition of code, make your programs much more readable and allow passing of parameters to increase flexibility.

The advantages of subroutines include:

Many of the built-in functions with Perl are little more than pre-coded subroutines.

sub myFunction
{
  print("Hello World");

}

The above example gives the basic syntax for declaring a subroutine. The subroutine name follows the 'sub' keyword and the block of code is contained in the following braces.

print(average(1, 3, 8, 2));

sub average
{
  foreach $_ (@_)
  {
    $total += $_;
    $i++;
  }
  $avg = $total / $i;
  return $avg;
}

This example demonstrates the use of parameters. In this instance we have not declared the parameters so Perl assumes them from their usage. We have passed an array, or list, of values to the subroutine to calculate the average of the values. Note the use of the 'return' keyword to pass the end value back from the routine. In other languages, a routine that returns a value is called a function.

Scope of Variables

Perl variables are global in scope, meaning they have value throughout the whole of the code. Other languages keep variable declared within a subroutine as private to that routine. The 'my' operator permits this scope limiting in Perl, A variable declared as: 'my $myVar = 1;' will be local to the routine that it was declared in.

The 'use strict' pragma can direct the interpreter to ensure that all variables are declared with the 'my' operator. But this is a more advanced subject and will be covered later.

Design by Stephen

Certified Internet Webmaster

Page last Edited: 10 Nov 2011