2.4 Using require

Suppose 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,[5] you'll get a warning from Perl that you've redefined the subroutine, even though it's the same definition.

[5] You are using warnings, right? You can enable them with either -w or use warnings;.

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.[6] 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 .

[6] In the %INC hash, as described in the entry for require in the perlfunc documentation.

Figure 2-2. Once the drop_anchor.pl file is brought in, another attempt to require the file is harmless

The require operator also has two additional features:

  • Any syntax error in the required file causes the program to die, thus the many die $@ if $@ statements are unnecessary.

  • The last expression evaluated in the file must return a true value.

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.