Tip #3 - Automated Requires
If you have a large number of subroutine files to be included in a program, the long list of
'require' statements can become cumbersome. Once you are 'requiring' more than two or three
files a different approach is desirable.
A touch of recursion will allow your program to automatically discover the files it needs
and include them without the need of listing multiple 'require' statements.
Another application of recursively including requires is when your program needs to be extensible. With proper architecture you can add options and/or commands to a program by simply writing the new
function as a subroutine and dropping it into the appropriate directory, whereby the program can simply
find it and include it on startup.
If the files are in a single subdirectory, the process is simple, but if you have a variety of functions of different categories, you can almost as easily process files from many different directories.
The example code snippit assumes a dynamically extensible program with files located in multiple sub directories to be included at startup. It functions by creating an array of directory names "@dirs" and then recursively looping thru the array. This way new directories can be added easily, with no changes other than adding the directory name to the array.
For each directory name in the list, we obtain a directory listing of all the files in that directory, and then process the require statement for each file. Six lines of functional code can thus easily include hundreds or even thousands of files.
#Include all the subroutine files in the
Handlers, Commands, and Extras directories.
@dirs = ("handlers","commands","extras");
foreach $dir (@dirs) {
opendir(DIR, "./$dir");
foreach $file (sort(grep(!/^\./, readdir(DIR)))) {
print "Including $file..";
require "$dir/$file";
print " OK!\n";
}
closedir(DIR);
}
A less complex version could be used to require only files from a single directory. Simply delete the first "foreach" loop and the "@dirs" array, replacing the "./$dir" in the opendir statement with the name of the single directory.
|