2.4. Using requireSuppose navigate.pl itself also pulls in drop_anchor.pl for some common navigation task. You'll end up reading the file once directly, and then again while processing the navigation package. This will needlessly redefine drop_anchor( ). Worse than that, if warnings are enabled,[8] you'll get a warning from Perl that you've redefined the subroutine, even though it's the same definition.
What you need is a mechanism that tracks what files have been brought in and bring them in only once. Perl has such an operation, called require. Change the previous code to simply: require "drop_anchor.pl"; require "navigate.pl"; The require operator keeps track of the files it has read.[9] Once a file has been processed successfully, any further require operations on that same file are simply ignored. This means that even if navigate.pl contains require "drop_anchor.pl", the drop_anchor.pl file is brought in exactly once, and you'll get no annoying error messages about duplicate subroutine definitions (see Figure 2-2). Most importantly, you'll also save time by not processing the file more than once .
Figure 2-2. Once the drop_anchor.pl file is brought in, another attempt to require the file is harmlessThe require operator also has two additional features:
Because of the second point, most files evaluated for require have a cryptic 1; as their last line of code. This ensures that the last evaluated expression is in fact true. Try to carry on this tradition as well. Originally, the mandatory true value was intended as a way for an included file to signal to the invoker that the code was processed successfully and that no error condition existed. However, nearly everyone has adopted the die if ... strategy instead, deeming the "last expression evaluated is false" strategy a mere historic annoyance. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|