Subroutines #1

#0 | #1 | #2 | #3 | #4

As you begin programming larger projects, you will find yourself writing code to do a task, but if you need to do that task several times, you start thinking about a way to reduce the amount of code you type.

Of course, you can always copy-paste the code from one place to another in your code - even from one file to another. But that seems like a kludgy way to do things. Every programming language has the ability to create subroutines.

Subroutines (also known as functions) are pieces of code that you can use over and over again, in several different scripts, without copying and pasting the same code over and over.

An important feature of a subroutine is that it usually performs just one task.

So you have a Perl script, and want to print a message on the screen every time it runs. Not a hard bit of code to write, but since this is about subroutines ...

The message you want to print is "Hey, I'm a subroutine!".

Subroutines are created and used a number of ways in Perl, but a simple way to create one like ours follows this format:

sub NAME BLOCK

So we need a name for our subroutine, and a block of code that does something.

sub announce
{
    print "Hey, I'm a subroutine!\n";
}

When naming your subroutines, be careful not to use the name of an already existing Perl function of key word. This will create problems you do not need right now.

Place that code somewhere in your script - I typically place them at the end so it's easier to find. Don't worry about having to put it at the beginning of your script. Some programming languages require that the definition and declaration of a subroutine appear BEFORE you call it. Perl will find it regardless where you put it.

Now to print your message, you call your subroutine in your script where-ever you want to print your message.

#!/usr/bin/perl
use strict;
use warnings;

announce(); # <--- calling the subroutine

########################## subroutines #####################
sub announce
{
    print "\nHey, I'm a subroutine!\n\n";
    
}

Note that we included parentheses () in our code when calling the subroutine. Subroutines can perform many operations, and may require that we pass it some arguments or parameters to use. Calling it this way means we are not passing it anything.

If you run that script, you will see the message printed out. But if that's all a subroutine could do there's not much point in it. Our next few pages will develop some ways to use subroutines that are a bit more useful.