Modules

require#

Load a Perl source file at runtime, or demand a minimum Perl version.

require has three forms that do quite different things. With a version number it asserts the running interpreter is new enough. With a bareword it loads a module by transforming Foo::Bar into Foo/Bar.pm and searching @INC. With a runtime string or $_ it loads a filename verbatim. All three are runtime operations — contrast with use, which is require + import wrapped in a compile-time BEGIN block.

Synopsis#

require VERSION
require EXPR
require

What you get back#

For the version-check form: 1 if the running Perl is new enough; otherwise an exception is thrown (Perl vX.Y.Z required--this is only ...). Nothing to check.

For the file-loading forms: the true value returned by the last statement of the loaded file, or 1 if the file enables the module_true feature (default under use v5.38 and later). A second require of the same path returns 1 without re-executing the file. Failure throws an exception — either the compile/runtime error from the file, Can't locate Foo/Bar.pm in @INC ..., or Foo/Bar.pm did not return true value.

Wrap in eval when you want to test whether a module is loadable:

eval { require Some::Optional::Module };
if ($@) { ... }                    # module missing or broken

Global state it touches#

  • @INC — the search path for bareword and relative-filename forms. Entries may be directory strings, coderefs, array refs, or blessed objects (see @INC hooks below).

  • %INC — maps the requested filename (Foo/Bar.pm) to the absolute path that was loaded. require consults it to avoid double-loading and sets it on success. An entry of undef marks a file whose compilation failed.

  • $_ — used as the filename when require is called with no argument.

  • ${^HOOK}{require__before} and ${^HOOK}{require__after} — optional coderefs run around every require, available for tracing and instrumentation wrappers.

The three forms#

require VERSION — minimum Perl check#

VERSION is either a v-string like v5.38.0 (compared against $^V) or a numeric literal like 5.038000 (compared against $]). If the running interpreter is older, require throws.

require v5.38;        # preferred
require 5.038;        # numeric; same effect
require 5.038_000;    # same; pre-5.6 syntax

This is a runtime check. If you want the check to happen at compile time (so the script never starts up on an old Perl), use use VERSION instead:

use v5.38;            # compile-time equivalent

require EXPR where EXPR is a bareword — module by name#

A bareword is interpreted as a module name. require replaces every :: with / and appends .pm, then searches @INC:

require Foo::Bar;     # looks for Foo/Bar.pm in @INC

This form also autovivifies the stash at compile time — the Foo::Bar:: package hash springs into existence even if the load later fails. No symbols are imported; require only loads code.

Before trying Foo/Bar.pm, require looks for Foo/Bar.pmc in the same directory and prefers it if found. The .pmc hook lets build tools ship precompiled companion files alongside sources.

require EXPR where EXPR is a string — file by path#

Any non-bareword expression is treated as a literal filename. No :: translation, no .pm appending, no stash autovivification:

require "Foo/Bar.pm";           # explicit .pm path
require "$config_dir/init.pl";  # arbitrary filename

my $class = 'Foo::Bar';
require $class;                 # ERROR: looks for file "Foo::Bar"

The last line is the classic trap: once the module name is in a scalar, it is a string, not a bareword. To load a module whose name is computed, either do the translation by hand or go through eval:

(my $file = "$class.pm") =~ s{::}{/}g;
require $file;

eval "require $class; 1" or die $@;

If EXPR is omitted entirely, $_ is used.

The %INC guard — loaded files stay loaded#

Before searching @INC, require consults %INC. If the requested filename is present and has a true value, require returns 1 immediately without re-reading the file. If the value is undef, a previous load failed and require throws Compilation failed in require — Perl refuses to retry a file that has already blown up once in this interpreter.

This means a module’s top-level code runs exactly once per interpreter, no matter how many places require it. Setup in a module’s file body is a one-shot operation; do not rely on it running for every require call in every caller.

A hook is free to set %INC itself; if it does not, require records the hook as the “source” of the load.

The 1; convention#

Historically every loadable file had to return a true value as its last expression, or require threw filename did not return true value. The canonical way to guarantee this is a trailing 1;:

package My::Thing;
# ... module code ...
1;                                 # mandatory, pre-5.38

As of Perl 5.38 the module_true feature — enabled by default under use v5.38 or later — makes every required file implicitly return true on successful compilation. Files that opt in no longer need 1;. Files that don’t, still do.

This only affects the compilation unit that turned the feature on; legacy modules loaded by a modern caller still need their own 1;.

When the loaded file does return a value and module_true is off, that value is what require returns — but only on the first load. Subsequent require calls of the same file return 1 from the %INC cache. To capture a file’s return value reliably, use do:

my $config = do "config.pl"
    or die "config.pl: ", $@ || $!;

@INC hooks — coderefs, array refs, and objects#

Entries in @INC do not have to be directory strings. A reference stored in @INC is called a hook and gets a chance to satisfy the require.

Subroutine reference#

Called with two arguments: the coderef itself and the filename (Foo/Bar.pm). It should return either nothing (meaning “I can’t handle this; try the next entry”) or up to four values:

  1. A scalar reference to source text prepended to the file.

  2. A filehandle the rest of the source is read from.

  3. A generator or filter subroutine (see perldoc perlfunc for the exact protocol).

  4. Optional state passed back to the generator.

push @INC, sub {
    my ($self, $filename) = @_;
    return unless $filename eq 'Virtual/Module.pm';
    open my $fh, '<', \"package Virtual::Module; 1;";
    return $fh;
};

Array reference#

The first element is a coderef or object as above; the rest is state the hook can read on each call. When the first element is an object with an INC or INCDIR method, the method receives the array ref as its third argument.

push @INC, [\&my_loader, $db_handle, $cache];

Blessed object#

If the object has an INC or INCDIR method, require calls that method; otherwise, if the object is also a coderef, it’s invoked like a plain subroutine reference. INC methods must be declared with their fully qualified name (sub Foo::INC { ... }), because the unqualified symbol INC is hard-wired to package main.

A hook may freely update %INC to record the path it supplied; if it doesn’t, require stores the hook reference itself.

require vs use#

use Foo::Bar qw(x y);

# is almost exactly:

BEGIN {
    require Foo::Bar;
    Foo::Bar->import(qw(x y));
}

Aspect

use

require

When it runs

Compile time (inside BEGIN)

Runtime

Calls import

Yes

No

Bareword ::/

Yes

Yes, when called on a bareword

Version check form

use v5.38

require v5.38

Good for

Fixed dependencies

Optional / late-bound modules

Reach for require when the module is optional, loaded from a computed name, or loaded only inside a branch that may never run. Reach for use for everything else.

Examples#

Minimum Perl version at runtime:

require v5.38;

Bareword module load — searches @INC, autovivifies Data::Dumper:: at compile time:

require Data::Dumper;
Data::Dumper->import;
print Data::Dumper::Dumper(\%ENV);

Optional module — fall back gracefully when missing:

my $have_json = eval { require JSON::PP; 1 };
if ($have_json) {
    print JSON::PP->new->encode($data);
}

Load a module whose name is computed at runtime. Convert to a filename path; require $class would search for a literal file named Foo::Bar:

my $driver = $ENV{DB_DRIVER} // 'SQLite';
my $class  = "DBD::$driver";
(my $file  = "$class.pm") =~ s{::}{/}g;
require $file;

Load a configuration fragment by pathname, keeping its return value — note the do, not require, because we want the value every call:

my $config = do '/etc/myapp/config.pl'
    or die "config load failed: ", $@ || $!;

Install an @INC hook that serves a single virtual module from an in-memory string:

unshift @INC, sub {
    my ($self, $filename) = @_;
    return unless $filename eq 'MyApp/Version.pm';
    my $src = "package MyApp::Version; our \$VERSION = '1.23'; 1;";
    open my $fh, '<', \$src;
    $INC{$filename} = '(generated)';
    return $fh;
};
require MyApp::Version;

Edge cases#

  • Bareword vs string: require Foo::Bar and require "Foo::Bar" are not the same. The bareword form translates to Foo/Bar.pm; the string form looks for a file literally named Foo::Bar.

  • Computed class names: require $class where $class holds 'Foo::Bar' searches for a file named Foo::Bar, not Foo/Bar.pm. Translate the name yourself, or use eval "require $class" when the name is trusted.

  • No argument: require; uses $_ as the filename. Rare in modern code; almost always an accident.

  • Second-chance retries don’t work: If a require fails partway through compilation, %INC records undef for that filename. A later require of the same name sees the undef and throws Compilation failed in require without re-running the file. Delete the %INC entry if you genuinely want to retry (this is a sharp edge; prefer fixing the underlying failure).

  • Relative . removal: . was removed from the default @INC in Perl 5.26. A script that used to find Foo/Bar.pm next to itself now has to add its own directory explicitly (use FindBin; use lib $FindBin::Bin;).

  • .pmc shadowing: If Foo/Bar.pmc exists in the same directory as Foo/Bar.pm, the .pmc wins. Stale .pmc files are a classic “why is my edit not taking effect” trap.

  • Parsing require(EXPR): require is parsed as a named unary operator; require EXPR + 1 means require(EXPR + 1). Use explicit parentheses when the argument is a non-trivial expression.

  • Stash autovivification: require Foo::Bar creates the Foo::Bar:: stash even if the file is missing. Downstream defined &Foo::Bar::some_sub checks may pass the “package exists” stage but fail the “sub exists” stage.

  • Filehandle from a hook must be real: Tied filehandles are silently ignored by the hook protocol; processing falls off the end and require reports “not found”. Use a real typeglob.

  • INC must be fully qualified in hook classes: sub Foo::INC { ... } works; sub INC { ... } inside package Foo installs main::INC because of a hard-coded package rule.

  • require() is hard to wrap: Many modules inspect the call stack to find their caller. A wrapper that adds a frame often breaks them. Prefer the ${^HOOK}{require__before} / ${^HOOK}{require__after} hooks (added in 5.38) for tracing.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • use — compile-time require + import; the normal way to pull in a module you depend on unconditionally

  • do — load a file and return its value on every call, with no %INC caching and no “must return true” rule

  • import — the method use calls after require; require never calls it for you

  • @INC — search path consulted for bareword and relative-filename loads; accepts directory strings, coderefs, array refs, and objects as hooks

  • %INC — one-entry-per-loaded-file cache that makes require idempotent and records where each module came from

  • eval — wrap require when the load is allowed to fail