Tip #4 - Verify Presence of Required Files
If you require a file in your program and the file is not present, your program will die unceremoniously. Exactly how it dies depends on where the file is used and how you require it.
A more elegant approach is to test for the presence of necessary files and directories at startup time and abort gracefully if they don't exist.
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.
|