Perl – use, require, import, and do

9 May 2009

Some notes on Perl’s use, require, import and *do. *Quick notes for me; not meant to be authoritative.

  • use is done at ‘compile-time’ and require is done at ‘run-time’ (ie can conditionally load modules)
  • require is the older method, but use uses require to do it’s work:
use Foo;
# equivalent to:
require Foo; Foo->import();

use Foo qw (foo bar);
# equivalent to:
require Foo; Foo->import(qw(foo bar));

use Foo();
# equivalent to:
require Foo;
# ie don't import anything, not even the default things
  • a Library is a just a file of code; a Module has package Foo in it (and usually other stuff)
  • use only works with modules, whereas require works with both modules and libraries. Corollary: use only works with module names (Foo), whereas require also works with paths (eg ~/lib/
  • require Foo will check if Foo has already been loaded, whereas **do Foo **will unconditionally reload Foo
  • better practice is to write modules rather than librarys, to prevent namespace pollution. A simple module:
package Foo;                   # minimal. Usually add things like:
use base qw (Exporter);
our @EXPORT = qw(qux slarken); # keep this list small - namespace pollution
  • to use this module:
use lib '~/lib';    # add this to %INC
use Foo;            # loads module, imports symbols in @EXPORT
Foo->bar();         # correct
Foo::bar();         # works, but not for inherited methods
qux();              # works, due to export
bar();              # carks

Some links:

comments powered by Disqus

  « Previous: Next: »