use and require
use loads a module at compile time, and require loads it while the program runs.
In this page:
use and require
use Module LIST is equivalent to a require followed by a call to the module's import method, and it happens at compile time inside an implicit BEGIN block. require Module loads it at run time and does not import anything, so you call functions by their full names. Because require can fail, it is often placed in an eval to load an optional module only when it exists.
Note:
use Module () loads the module without calling import at all, while use Module qw(name) imports only the named functions.
Example: use and require
use strict;
use warnings;
use List::Util qw(sum);
print "use imported sum: ", sum(1, 2, 3), "\n";
require File::Basename;
print "basename: ", File::Basename::basename("/tmp/report.txt"), "\n";
my $has_missing = eval { require Some::Missing::Module; 1 } ? "yes" : "no";
print "Some::Missing::Module available: $has_missing\n";
my $has_posix = eval { require POSIX; 1 } ? "yes" : "no";
print "POSIX available: $has_posix\n";
BEGIN { print "this line runs first, at compile time\n"; }
print "then the normal code runs\n";
# Output:
# this line runs first, at compile time
# use imported sum: 6
# basename: report.txt
# Some::Missing::Module available: no
# POSIX available: yes
# then the normal code runs
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting use to run at the place where it is written instead of at compile time
- Calling imported function names after require without importing them
- Importing everything when you only need one or two functions
Chapter Summary
- use runs at compile time and imports
- require runs at run time
- eval { require Module } tests for a module
- Import only the names you need
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: