Section 10.4.  Using require

Table of Contents

10.4. Using require

Suppose navigation.pm itself also pulls in drop_anchor.pm for some common navigation task. Perl reads the file once directly and then again while processing the navigation package. This needlessly redefines drop_anchor( ). Worse than that, if we have warnings enabled,[*] we'll get a warning from Perl that we've redefined the subroutine, even if it's the same definition.

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

We need a mechanism that tracks which files we've brought in and then brings them in only once. Perl has such an operation, called require. Change the previous code to simply:

require 'drop_anchor.pm';
require 'navigation.pm';

The require operator keeps track of the files Perl has read.[Section 10.4.  Using require] Once Perl has processed a file successfully, it simply ignores any further require operations on that same file. This means that even if navigation.pm contains require "drop_anchor.pm", Perl imports the drop_anchor.pm file exactly once, and we'll get no annoying error messages about duplicate subroutine definitions (see Figure 10-2). Most importantly, we'll also save time by not processing the file more than once.

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

Figure 10-2. Once Perl brings in the drop_anchor.pm file, it ignores another attempt to require it

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.

Table of Contents
© 2000- NIV