Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 43 ยท Modules and Errors

Packages and Modules

Organize Perl code with packages and modules: use versus require, the @INC search path, Exporter, writing your own .pm file and a tour of useful core modules.

A small script fits in one file. A real program does not. Perl lets you split code into modules, files that each define a package (a namespace) and can be loaded from any script with use. Modules keep names from colliding, make code reusable, and are how you consume everything on CPAN. Perl also ships with hundreds of core modules, so a lot of useful code is already on your machine.

This lesson explains packages, how Perl finds and loads modules, how to write and export from your own module, and which core modules are worth knowing first.

Perl is not installed on this site, so the Perl code is read-only (its output was captured from a real run). The interactive examples are Python and Bash stand-ins for the same ideas.

Packages are namespaces

A package is a named group of variables and subroutines. The package statement switches the current namespace. Names inside it are reached from outside with ::.

PERL
use v5.36;

package Counter {
    my $n = 0;                    # private to this block
    our $label = 'hits';          # package variable: $Counter::label
    sub next_id { return ++$n }
}

say Counter::next_id();   # 1
say Counter::next_id();   # 2
say $Counter::label;      # hits
say __PACKAGE__;          # main

Code that does not declare a package lives in main. The block form package Name { ... } limits the package to the braces. Package names are conventionally written Like::This, and they map straight onto file paths: My::Greeter lives in My/Greeter.pm.

A package is only a namespace. It becomes a class when you add objects (see Classes and Objects) and a module when it lives in its own .pm file that other programs load.

Package, module, library

Package A namespace for names.
Module A .pm file with one package.
Distribution Modules shipped together, like on CPAN.
1 / 2

use versus require

Both load a module, but at different times.

  • use Module LIST; runs at compile time. It loads the file and then calls the module's import method with the list, which is how names get exported to you. Use it at the top of a file.
  • require Module; runs at run time, when execution reaches it. It loads the file but does not call import. Use it for optional modules or for loading something only when needed.
PERL
use List::Util qw(sum max);        # imports sum and max now

if ($want_json) {
    require JSON::PP;              # loaded only on this path
    my $text = JSON::PP->new->encode($data);
}

my $ok = eval { require Some::Optional; 1 };
say $ok ? 'available' : 'not installed';

require dies when the file cannot be found, with a message like Can't locate Some/Optional.pm in @INC. Wrapping it in eval turns that failure into a value you can test, a common way to support optional dependencies. A written-out form use Module () loads the module but imports nothing, and use Module 1.5 checks that its $VERSION is at least 1.5.

Where Perl looks: @INC and %INC

When you load My::Greeter, Perl converts the name to My/Greeter.pm and tries every directory in the array @INC in order. The first match wins and its path is stored in the hash %INC, which is also how Perl knows a file has already been loaded.

You can add a directory without editing your environment:

PERL
use FindBin qw($Bin);
use lib "$Bin/lib";            # search ./lib next to the script

Other ways are the -I command line switch (perl -Ilib script.pl) and the PERL5LIB environment variable. To see the current list run perl -e 'print "$_\n" for @INC'.

Bash Stand-in: turning a module name into a path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The same rule, written in Perl, is simply s{::}{/}g followed by .pm.

Writing your own module

Create lib/My/Greeter.pm. A module is a package whose file ends with a true value (1;). To share subroutines, use the standard Exporter module.

PERL
package My::Greeter;
use v5.36;
use Exporter 'import';

our @EXPORT_OK   = qw(greet shout);
our %EXPORT_TAGS = (all => \@EXPORT_OK);
our $VERSION     = '1.02';

sub greet ($name) { return "Hello, $name!" }
sub shout ($text) { return uc($text) . '!' }

1;

Then use it from a script:

PERL
use v5.36;
use FindBin qw($Bin);
use lib "$Bin/lib";
use My::Greeter qw(greet shout);

say greet('Ana');          # Hello, Ana!
say shout('hey');          # HEY!
say My::Greeter->VERSION;  # 1.02

The two export arrays do different jobs:

  • @EXPORT names are exported to every caller by default. Avoid it: it pollutes the caller's namespace and you cannot take names back later.
  • @EXPORT_OK names are exported only when the caller asks for them. This is the polite default.
  • %EXPORT_TAGS groups names so a caller can write use My::Greeter qw(:all).

If you export nothing, callers use the full name: My::Greeter::greet('Ana'). Many modules do this on purpose, especially object-oriented ones.

Python Stand-in: a module with a public API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Good module habits

  • Start every module with use strict and use warnings, or a single use v5.36; (see use strict and use warnings).
  • End the file with 1; so loading counts as success.
  • Keep one package per file, named to match the path.
  • Put a $VERSION in each module so callers can require a minimum.
  • Document it with POD, Perl's built-in documentation format, so perldoc My::Greeter works.

Tests normally live in a t/ directory next to lib/, which is the subject of Testing with Test::More.

A tour of useful core modules

These modules come with Perl, so nothing needs installing.

Data helpers

List::Util sum, max, first, uniq, reduce, any.
Scalar::Util blessed, reftype, looks_like_number, weaken.
Data::Dumper Print any structure.
JSON::PP Encode and decode JSON.
1 / 2
PERL
use v5.36;
use List::Util qw(sum max min first uniq reduce any);
use Scalar::Util qw(blessed looks_like_number reftype);

say sum(1..4);                       # 10
say max(3, 9, 2);                    # 9
say min(3, 9, 2);                    # 2
say first { $_ > 2 } (1..5);         # 3
say join ',', uniq(1, 1, 2, 3, 3);   # 1,2,3
say reduce { $a * $b } 1..5;         # 120
say((any { $_ == 2 } 1, 2, 3) ? 'yes' : 'no');   # yes

say looks_like_number('1e3') ? 1 : 0;   # 1
say looks_like_number('abc') ? 1 : 0;   # 0
say reftype([]);                        # ARRAY
say blessed([]) // 'not an object';     # not an object

Getopt::Long turns command line switches into variables. A ! after a name makes a negatable flag, =s expects a string and =i an integer.

PERL
use Getopt::Long;

GetOptions(
    'name=s'  => \my $name,
    'verbose!' => \my $verbose,
    'n=i'     => \my $n,
) or die "bad options\n";

# perl tool.pl --name Zed --verbose --n 3 file.txt
# $name is 'Zed', $verbose is 1, $n is 3, @ARGV is ('file.txt')

File::Temp creates temporary files that are removed automatically, and Time::HiRes gives fractional seconds for timing:

PERL
use File::Temp qw(tempfile);
use Time::HiRes qw(time sleep);

my ($fh, $filename) = tempfile(UNLINK => 1);
print $fh "scratch data\n";
close $fh;

my $start = time;
sleep(0.01);
printf "%.2f seconds\n", time - $start;

You can read the documentation of any of them with perldoc List::Util, and list what is installed through perldoc perlmodlib. Third-party modules arrive through CPAN, covered next in CPAN and Dependency Management.

Common mistakes

  • Forgetting 1; at the end of a module: the load fails with "did not return a true value".
  • Exporting by default with @EXPORT, which causes name clashes.
  • Calling require and expecting imports. require never calls import.
  • Circular use between two modules, which leaves one half-loaded. Move the shared code to a third module.
  • Wrong file path. My::Greeter must be found at My/Greeter.pm under some @INC directory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between use Module and require Module?

    use is processed while the program compiles and calls the module's import method. require runs when execution reaches it and loads the file without importing.
  2. 2. Which file does Perl load for use My::Greeter;?

    Package separators become slashes and .pm is appended. Perl looks for My/Greeter.pm in each @INC directory.
  3. 3. Why is @EXPORT_OK usually better than @EXPORT?

    @EXPORT pushes names into every caller whether wanted or not. @EXPORT_OK keeps the choice with the caller.
  4. 4. What does the 1; at the end of a .pm file do?

    A module file must evaluate to a true value as its last statement, otherwise require reports that it did not return a true value.
  5. 5. How do you add a project's lib directory to the module search path from inside a script?

    use lib adds directories to the front of @INC. Combined with FindBin it works regardless of the current directory.

Summary

  • A package is a namespace; a module is a .pm file that defines one, ending in 1;.
  • use loads at compile time and calls import; require loads at run time and is good for optional modules.
  • Perl searches @INC for My/Greeter.pm and records loaded files in %INC; extend the path with use lib, -I or PERL5LIB.
  • Share subroutines with Exporter, preferring @EXPORT_OK and %EXPORT_TAGS.
  • Core modules such as List::Util, Scalar::Util, Getopt::Long, File::Temp and Time::HiRes cover many everyday jobs.

Next, learn how to find and install third-party code in CPAN and Dependency Management.