TExcelTAD
Home › Perl › Packages and Modules

Packages and Modules

As programs grow, you need to organise code and avoid name clashes. Perl does this with packages (namespaces) and modules (files containing a package, loaded with use).

Packages are namespaces

package NAME; switches the current namespace. Subs and package variables defined afterwards belong to that package, and you call them with their full name Package::function:

perl · try it yourself
use strict;
use warnings;

package Temperature;

sub c_to_f { return $_[0] * 9 / 5 + 32 }
sub f_to_c { return ($_[0] - 32) * 5 / 9 }

package Distance;

sub km_to_miles { return $_[0] * 0.621371 }

package main;          # back to the default package

print "25 C = ", Temperature::c_to_f(25), " F\n";
print "212 F = ", Temperature::f_to_c(212), " C\n";
printf "10 km = %.2f miles\n", Distance::km_to_miles(10);
print "Current package: ", __PACKAGE__, "\n";
25 C = 77 F
212 F = 100 C
10 km = 6.21 miles
Current package: main

Code outside any package statement lives in main. __PACKAGE__ gives the name of the current package.

The block form package NAME { ... } limits the package to the braces, which is tidier when several packages share a file:

perl · try it yourself
use strict;
use warnings;

package Greeter {
    our $VERSION = '1.02';
    sub hello { my ($who) = @_; return "Hello, $who!" }
}

print Greeter::hello("modules"), "\n";
print "Greeter version $Greeter::VERSION\n";
Hello, modules!
Greeter version 1.02

Modules are files

A module is a file named after its package: package My::Tools lives in My/Tools.pm somewhere in Perl's search path (@INC). It must end with a true value, traditionally 1;. A typical module that exports functions looks like this:

perl
# File: lib/My/Tools.pm
package My::Tools;
use strict;
use warnings;
use Exporter 'import';

our $VERSION   = '0.01';
our @EXPORT_OK = qw(trim commify);   # exported only on request

sub trim    { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s }
sub commify { my $n = reverse shift; $n =~ s/(\d{3})(?=\d)/$1,/g; return scalar reverse $n }

1;

And a script that uses it:

perl
#!/usr/bin/env perl
use strict;
use warnings;
use lib 'lib';                       # add ./lib to @INC
use My::Tools qw(trim commify);

print trim("  hi  "), "\n";
print commify(1234567), "\n";

use Module LIST; happens at compile time: Perl finds the file, runs it once, and calls Module->import(LIST), which (through Exporter) copies the requested subs into your namespace.

Seeing import in action

The online runner only accepts one file, but we can simulate a module by defining the package in the same file and calling import ourselves (which is exactly what use does):

perl · try it yourself
use strict;
use warnings;

BEGIN {
    package Text::Helpers;
    use Exporter 'import';
    our @EXPORT_OK = qw(shout whisper);
    our %EXPORT_TAGS = (all => \@EXPORT_OK);

    sub shout   { return uc($_[0]) . "!" }
    sub whisper { return lc($_[0]) . "..." }

    $INC{'Text/Helpers.pm'} = __FILE__;      # pretend the file was loaded
}

use Text::Helpers qw(:all);

print shout("watch out"), "\n";
print whisper("SECRET"), "\n";
WATCH OUT!
secret...

The BEGIN block runs the package code at compile time, before the use line is processed, and $INC{...} tells Perl the module is already loaded.

@EXPORT vs @EXPORT_OK

Variable Meaning
@EXPORT exported automatically by a plain use Module; (use sparingly: it pollutes namespaces)
@EXPORT_OK exported only when the user asks: use Module qw(name);
%EXPORT_TAGS named groups: use Module qw(:all);

use Module (); (an empty list) loads the module but imports nothing; you then call functions by their full name.

Core modules you already used

Perl ships with hundreds of core modules. You have already seen several:

perl · try it yourself
use strict;
use warnings;
use List::Util qw(sum0 max);
use POSIX qw(floor);
use Scalar::Util qw(looks_like_number);

print "sum0 of nothing: ", sum0(), "\n";
print "max: ", max(3, 9, 2), "\n";
print "floor(2.7): ", floor(2.7), "\n";
for my $v ("42", "4.2e3", "forty") {
    print "$v looks like a number? ", (looks_like_number($v) ? "yes" : "no"), "\n";
}
sum0 of nothing: 0
max: 9
floor(2.7): 2
42 looks like a number? yes
4.2e3 looks like a number? yes
forty looks like a number? no

Thousands more are on CPAN, installed with cpan Module::Name or cpanm Module::Name. (The examples on this site use core modules only.)

Test yourself

Which file should hold the package Shop::Cart?

  1. Shop-Cart.pm
  2. Shop/Cart.pm
  3. Cart.pl
  4. shop_cart.pm

Why do modules traditionally end with 1;?

  1. To set the version
  2. Because the file must return a true value when loaded
  3. To export functions
  4. It marks the end of POD

What does use Module qw(f); do with f, if f is in @EXPORT_OK?

  1. Nothing
  2. Imports f into your package so you can call it as f()
  3. Deletes f
  4. Renames the module