Organization of Subroutines

A solid programming strategy is to write programs in small, manageable, reusable pieces. This division of labor in Perl is accomplished through the use of programmer-written subroutines, operating system calls, built-in subroutines, and library functions. To the Perl programmer, they all look the same. Part 1 of this book concentrates on programmer-written subroutines.

Although programmer-written subroutines may be defined anywhere within a Perl script, in practice they are usually defined in separate files and then imported into any program that needs them. However, for simplicity, the first few subroutines that we demonstrate will be defined at the top of the file that needs them. The general form of a subroutine is as follows:

sub subName
{
    body of subroutine;
}

Once a subroutine is defined ahead of its first use, it can be invoked in any of the following ways; the last line is preferred.

&subName()
&subName
subName;
subName()

Here is an example of a subroutine. Each time it is called, it prints the company name, city, and state. See the folder Org.


% type org.pl
#
#       org.pl
#
sub header
{
        print "=============
";
        print "/training/etc
";
        print "Columbia, ";
        print "MD.
";
        print "=============
";
}
print "print the header
";
header();                    # call the subroutine
print "header is printed
";
% perl org.pl
print the header
=============
/training/etc
Columbia, MD.
=============
header is printed
%

When Perl executes your code, it skips over any subroutines and executes them only when they are invoked, as shown above. The subroutine named header works perfectly well as it is written, but it lacks generality. Users of this subroutine should be able to pass as arguments to the subroutine, for example, the company name, the city, and the state.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.254.35