Scoping · Modules · Classes and OO

use#

Load a module at compile time and import its symbols into the current package.

use is the everyday mechanism for pulling in library code. It runs at compile time, not at run time: the named module is located on @INC, loaded (if not already in %INC), and given a chance to alter the caller’s namespace — typically by aliasing subroutine or variable names into it. The same syntax also drives pragmas (compiler directives like strict or warnings); the only difference is convention — pragmas are lowercase and usually have lexical, not package-wide, effects.

A use statement is defined to be exactly equivalent to:

BEGIN { require Module; Module->import(LIST); }

The BEGIN forces both the load and the import to happen while the surrounding file is still being parsed, so the imported names are visible to the compiler for the rest of the file.

Synopsis#

use Module VERSION LIST
use Module VERSION
use Module LIST
use Module
use Module ()
use VERSION

What you get back#

use is a declaration, not an expression — it has no useful return value and cannot appear on the right-hand side of anything. Its effect is a side effect on the current compilation unit: package %INC gets an entry, the importing package gets whatever symbols import aliased in, and — for use VERSION — the current lexical scope gets a feature bundle turned on.

If the module cannot be loaded, or if import dies, the BEGIN block propagates the exception and compilation aborts.

The four module forms#

use Module#

Loads the module and calls its import method with no arguments. The module decides what “no arguments” means; for Exporter-based modules it typically means “export your @EXPORT defaults”:

use File::Spec;                 # calls File::Spec->import()

use Module LIST#

Loads the module and calls import with LIST:

use List::Util qw(first sum max);

This is the common “import exactly these names” form. LIST is passed verbatim to import; its meaning is the module’s business, not the language’s.

use Module ()#

Empty parentheses disable the import call entirely. This is distinct from omitting the list — no import method is invoked at all:

use POSIX ();                   # load, but do not import anything
POSIX::strftime(...);           # call by full name instead

Equivalent to:

BEGIN { require POSIX }

Use this when you want the module loaded but do not want your namespace altered — typically because you will call everything by fully qualified name, or because the module’s default exports would clobber something you care about.

use Module VERSION / use Module VERSION LIST#

When a VERSION appears immediately after Module (no comma), use calls the module’s VERSION method with that version as an argument before calling import:

use List::Util 1.45 qw(uniq);

is equivalent to:

BEGIN {
    require List::Util;
    List::Util->VERSION(1.45);
    List::Util->import(qw(uniq));
}

The default VERSION method, inherited from UNIVERSAL, croaks if the requested version is greater than $Module::VERSION.

VERSION must look like a version literal — a digit, or v followed by a digit. Arbitrary expressions in that position are parsed as the start of LIST, not as a version. Note there is no comma after VERSION.

use VERSION — request a Perl language level#

use VERSION (with no module name) declares the minimum Perl version the file requires, and lexically enables the matching feature bundle:

use v5.36;                      # v-string form — preferred
use 5.036;                      # numeric form — equivalent
use 5.036_000;                  # older numeric form

An exception is raised at compile time if the running Perl is older than VERSION; the rest of the file is not even parsed.

Beyond the version check, use VERSION turns on the features bundled with that release:

  • use v5.12 or higher — implicit use strict.

  • use v5.35 or higher — implicit use warnings.

  • use v5.36 — the common modern baseline: adds say, signatures, isa, and the earlier bundles’ features.

  • use v5.39 or higher — lexically imports builtin functions for the matching bundle.

  • use v5.41 or higher — enables source::encoding 'ascii'.

use VERSION does not load feature.pm, strict.pm, warnings.pm, or builtin.pm — it implements the equivalent behaviour directly. Place it at the top of the file, before anything that depends on those features being active.

From Perl 5.39 onward, issuing a second use VERSION while one is already in effect is a fatal error. In older bundles it was merely deprecated.

Modules vs pragmas#

Syntactically, pragmas and modules are identical — both are just packages whose import method you invoke via use. The conventional differences:

  • Naming. Pragmas are lowercase (strict, warnings, feature, integer); modules are Studly::Caps.

  • Scope of effect. Pragmas usually alter the current lexical scope (a block, not a package) and unwind at the closing brace. Modules usually alter the current package and persist until end-of-file.

  • no. The counterpart no statement calls unimport instead of import. Pragmas typically implement unimport to undo their effect; most ordinary modules do not.

use strict;                     # lexical — affects this block / file
use warnings;                   # lexical
{
    no warnings 'uninitialized';
    # warnings off only in this block
}

use List::Util qw(sum);         # package-scoped — affects main::

Conditional loading#

Because use runs at compile time, it ignores ordinary runtime control flow. A use inside the false branch of an if is still executed:

if (0) {
    use Heavy::Module;          # loaded anyway — compile time!
}

For genuinely conditional loading, either use require at run time, or delegate to the if pragma:

use if $] >= 5.036, 'experimental', 'builtin';
use if $^O eq 'MSWin32', 'Win32::API';

Examples#

Load a module with its default exports:

use Carp;                       # croak, carp, confess visible here

Import a specific subset:

use List::Util qw(first min max sum);

Load without importing — call by full name:

use Scalar::Util ();
my $ok = Scalar::Util::looks_like_number($x);

Require a minimum module version:

use Moo 2.000000;

Declare the Perl language level and pick up its feature bundle:

use v5.36;                      # strict, warnings, say, signatures...
sub greet ($name) {
    say "hello, $name";
}

Turn a pragma on for a file, then off for one block:

use warnings;

sub legacy_parser {
    no warnings 'uninitialized';
    return join ",", @_;        # undefs render as "" without warnings
}

Conditional pragma via the if helper:

use if $] < 5.010, 'MRO::Compat';

Edge cases#

  • Module must be a bareword. use $name; is a syntax error — use does not accept a runtime expression for the module name. Use require for that.

  • No comma between Module and VERSION. use List::Util 1.45 is a version check; use List::Util, 1.45 is a syntax error.

  • The version literal rule is strict. Anything that does not start with a digit or with v followed by a digit is parsed as the beginning of LIST, not as a version. use Module "1.45" passes the string "1.45" to import; it does not check a version.

  • Empty LIST vs omitted LIST. use Module; calls Module->import(). use Module (); does not call import at all. The distinction matters for modules whose import has side effects even with no arguments.

  • Missing import method. If the module does not define (and does not inherit) an import method, the call is silently skipped — no error, even if AUTOLOAD is defined.

  • use inside eval. BEGIN runs at compile time of the eval’d code, so eval "use Some::Module" delays loading until the eval runs. This is the common way to probe for an optional module at run time:

    eval { require Some::Module; Some::Module->import };
    my $have_it = !$@;
    
  • Ordering of use VERSION and other pragmas. Place use VERSION first, so the feature bundle is in effect before later pragmas (which may depend on it) run. A later no strict 'refs' still overrides the strictures implied by use v5.12+, but relying on that is discouraged.

  • Pragmas that look like modules. Some pragmas ship with a capitalised name (UNIVERSAL, Internals); some modules ship lowercase (if, lib, ok). The naming convention is a hint, not a rule — what matters is what the module’s import does.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • require — the run-time half of use; loads a module without invoking import, and accepts a runtime expression for the module name

  • no — the counterpart declaration; calls unimport instead of import to undo a pragma’s effect

  • import — not a built-in; an ordinary class method invoked by use, usually provided via inheritance from Exporter

  • package — declares the package whose namespace use will alter

  • @INC — the list of directories searched for the module file

  • %INC — records every file loaded by use or require, keyed by relative path