O'Reilly logo

Beginning Perl for Bioinformatics by James Tisdall

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Scoping and Subroutines

A subroutine is defined by the reserved word [3] for subroutine definitions, sub; the subroutine's name, in this case, addACGT; and a block , enclosed in a pair of matching curly braces. This is the same kind of block as the block used in a loop to group statements together.

In Example 6-1, the name of the subroutine is addACGT, and the block is everything after the name. Here is the subroutine definition again:

sub addACGT {
    my($dna) = @_;

    $dna .= 'ACGT';
    return $dna;
}

Now let's look into the block of the subroutine.

A subroutine is like a separate helper program for the main program, and it needs to have its own variables. You will use two types of variables in your subroutines in this book:[4]

  • Arguments passed in to the subroutine

  • Other variables declared with my and restricted to the scope of the subroutine

Arguments are the values given to a subroutine when it is used, or called. The values of the arguments are passed into the subroutine by means of the special variable @_, as you'll see in the next section.

Other variables a subroutine might use must be protected from interacting with variables in other parts of the program, so they have effect only within the subroutine's own scope. This is accomplished by declaring them as my variables, as will be explained shortly.

Finally, most subroutines return their results via the return function. This can return a single scalar as in return $dna in our subroutine addACGT, in a list of scalars as in return ($dna1, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required