Main Content

Loading external code into Perl from a nonstandard directory

Archive - Originally posted on "The Horse's Mouth" - 2009-06-12 16:35:49 - Graham Ellis

Here's a piece of Perl code that loads in an external module.

push(@INC, "/var/opt/OV/bin/OpC/monitor");
eval { require "monitor_utils.pm"; };
if ($@) {
  print STDERR "could not load monitor_utils.pm: $@\n";
  exit 1; }


It comes from a delegate's existing application, and is worthy of further comment:

• The @INC list is the places from which Perl loads modules, and the code adds an extra place to that list.

• require rather than use pulls the module in, since use happens at compile time, and so would happen BEFORE the extension to @INC.

• The require is within an eval so that any error condition can be trapped, rather than the code crashing, if it failed.

• $@ is the error report from the eval. If it's empty, that's good news.

• the application exits with a '1' error code if the require fails - at OS level, 1 is an error and 0 is a success.