Tip #2 - Call Subroutines in External Files
As you master the use of conventional subroutines within your programs, you
will quickly build a collection of your own special subroutines that you use over
and over in many different programs. As you re-create these subroutines in
slightly different contexts, you will accumilate different changes, subtle enhancements
and minor tweaks. You will soon have many different programs containing many slightly
different copies of the same subroutines.
Over time you will make minor changes or enhancements to some of these and all of these different versions of your subroutines will diverge, subtle bugs will creep in and in general you will lose control of your code.
One way to address this issue is to collect all of your common subroutines into a collection of "library" files and use the "Require" directive to cause Perl to treat this library as if it were a part of your source file.
Simply placing the keyword "require" followed by the filename of the library file causes Perl to read the external file exactly as if the text in that file were pasted into the main file at that point.
Looking at our example file, if we wanted to write another program that used the subroutine 'flagsToByte', rather than copy the subroutine from V572.pl to a new program, it would be better to create a library file named 'flagsToByte' and place the subroutine in it.
Then at the beginning of each program that calls this subroutine we place the line "require flagsToByte". Now any program we write can use the 'flagsToByte' code without any additional effort, and we always know that they are all using the same code.
Some programmers will build a single large file with their most commonly used subroutines,
name it "MySubs.pl' or something similar, and then routinely include this file in all their programs.
More sophisticated programmers will build general purpose subroutines and place them in dedicated files, one subroutine to a file, or a group of related subroutines in a file, and store them in a directory named 'My Subs' or similar, and then place require statements as needed.
This second approach may at first seem more cumbersome, but in reality it is far simpler and easier to use.
First, all your subroutines are in a common place, and show up in a directory listing. Any individual subroutine can be accessed, examined and edited independently of any other. And adding new subroutines does not require any editing of existing routines.
The major drawback seems to be the necessity for many 'require' statements to pull in all the subroutines you wish to use. In the next tip we will show you a painless way to make this happen automatically.
|