ClassHelper.org US Site  ClassHelper.org UK Site  
ClassHelper News
About ClassHelper.org
Our Education Blog
Free Math Resources
Free School Clip Art
Crossword Puzzles
Word Find Puzzles
Cryptogram Puzzles
Word Jumble Puzzles
Coloring Book Pages
Computer Science
View Our Sitemap
Privacy Policy

Valid XHTML 1.0 Transitional


Perl Subroutines and Code Reuse

What are subroutines, and why are they useful?

In programming terminology, a subroutine is a block of code that performs a specific task. A subroutine optionally accept input from another part of the program, and optionally return a value to the part of the program that called it. Here's an example of a program with a subroutine that adds two numbers and prints the result on the screen:

#!/usr/bin/perl -w

use strict;

my $sum;

$sum = &add_numbers(5, 15);
print "The sum is $sum.\n";

sub add_numbers
{
    my $num1;
    my $num2;
    my $sum;

    $num1 = $_[0];
    $num2 = $_[1];
    $sum = $num1 + $num2;

    return ($sum);
}
pparadis@ubuntu-devel:~$ ./example.pl 
The sum is 20.

Subroutines are declared with the sub statement, followed by the name of the subroutine. Variables declared inside a subroutine (or "sub" for short) using my are private to the sub, meaning they can't be used outside the sub. In fact, if you had scalars named $num1 and $num2 in the main program body, they would be considered totally separate from the ones declared inside the sub. For programs that require more than a few lines of code, breaking apart each step in the program into a separate sub can greatly simplify the development process, while reducing the chance of accidentally changing a key variable's value.

Subroutines are useful for reducing the total size of a program, while easing maintenance and reducing the potential for bugs. If you find yourself copying and pasting the same (or very similar) block of code in several places in a program, consider creating a subroutine that contains the required code and calling it whenever it's needed. As an added benefit, you can frequently use the same subroutine in several programs, with minimal modifications.

To call a sub, you use the "&" character in front of its name, followed by input values (called "parameters") in parentheses. Subs don't have to accept input; this is only necessary if you need to pass in data to be operated on. Data values are returned to the calling function via the return statement, followed by a list of values. Subs aren't required to return any value at all; this is up to the programmer. You could have a sub that perform file operations based on parameters passed in from another part of your program, for example. Still, it's a good idea to send a return value from every sub, traditionally a zero to indicate success and different values to indicate failure based on different conditions. Suppose your sub that writes information out to a file requires only numeric input, and other characters were detected in the values passed into it. You could return a code of "1" to tell the calling function why the sub didn't write out the file as requested.

To use the input passed into a sub, extract it from the special built-in array "@_" as shown in our example. This is an "anonymous" array private to the sub it's contained within. Each value passed into the sub is found in its own index in @_.

Introducing Recursion: Subroutines Calling Themselves

In programming, the concept of recursion is expressed as subrouintes or functions that call themselves instead of simply performing a task and returning control to the calling portion of the program. This can be very useful in applications that need to iterate over mathematical functions, or use the output of a subroutine as the input to the same sub for further processing. Let's look at an example that uses recursion to draw a simple ASCII triangle on the screen:

#!/usr/bin/perl -w

use strict;

&draw_triangle(0);

sub draw_triangle
{
    my $iterations = $_[0];
    my $chars;

    $iterations++;
    if ($iterations == 11)
    {
        return 0;
    }
    else
    {
        for ($chars = 0; $chars < $iterations; $chars++)
        {
            print " * ";
        }
        print "\n";
        &draw_triangle($iterations);
    }
}

Here's the output from our program:

 *
 *  *
 *  *  *
 *  *  *  *
 *  *  *  *  *
 *  *  *  *  *  *
 *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *  *  *

You may be wondering why using recursion is any better than using a simple print statement to achieve the same effect. If you were only interested in printing out ten rows of text, this approach would be overkill. However, if we needed to create a triangle consisting of thousands of characters, the method shown would be much more efficient. Many programming tasks can be viewed like this: the easy way, or the efficient way. The programmer must decide which path to take.

For many applications, such as fractal generation, recursion is absolutely required to solve the problem. Programs which require cyclical input, such as those that represent mathematical functions, require recursion because each step in the calculation process is dependent on the values obtained beforehand.

Perl Modules

In the world of Perl, "modules" are used to provide tidy containers for blocks of code that meet certain needs. Perl modules are separate files that end in a ".pm" extension, stored in subdirectories named after the module. These modules are frequently designed to be used by any program that needs them, and represent a key aspect of object-oriented programming in Perl. These concepts are beyond the scope of this tutorial, but links to resources that offer more information on Perl modules may be found in the last chapter.

The next chapter will show you how to create your first web application in Perl.

Continue: Your First Web Application

Table of Contents
  1. Introduction and Motivation
  2. System Requirements and Getting Perl
  3. Variables and Data Types
  4. Program Flow Control
  5. File Input/Output
  6. Subroutines and Code Reuse
  7. Your First Web Application
  8. Getting User Input with HTML Forms
  9. Coding Style and Maintenance
  10. Security Considerations
  11. Additional Programming Resources