@INC and finding modules
Perl searches a list of directories, @INC, to find each module you load.
In this page:
@INC and finding modules
When you write use Some::Module, Perl converts the name to Some/Module.pm and looks for it in each directory of @INC in order. Once loaded, the file is recorded in the %INC hash so it is not loaded twice. You can add your own directory with use lib dir or by changing @INC before the require, and the PERL5LIB environment variable also adds directories.
Note:
use lib runs at compile time, so it works with a use statement, while changing @INC at run time only helps a later require.
Example: @INC and finding modules
use strict;
use warnings;
my $dir = "demo_lib";
mkdir $dir unless -d $dir;
open(my $fh, '>', "$dir/Hello.pm") or die "Cannot write module: $!";
print $fh "package Hello;\nsub greet { return 'Hello from a module file'; }\n1;\n";
close $fh;
print "Hello.pm loaded before? ", (exists $INC{'Hello.pm'} ? "yes" : "no"), "\n";
unshift @INC, $dir;
require Hello;
print Hello::greet(), "\n";
print "loaded from: $INC{'Hello.pm'}\n";
print "first \@INC entry: $INC[0]\n";
print "module path for Data::Dumper: ", join('/', split(/::/, 'Data::Dumper')) . ".pm", "\n";
unlink "$dir/Hello.pm";
rmdir $dir;
# Output:
# Hello.pm loaded before? no
# Hello from a module file
# loaded from: demo_lib/Hello.pm
# first @INC entry: demo_lib
# module path for Data::Dumper: Data/Dumper.pm
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Naming the file differently from the package name
- Changing @INC at run time and then using use
- Expecting a module to be reloaded by a second require
Chapter Summary
- @INC lists the directories searched
- %INC records loaded files
- use lib adds a directory
- Module names map to file paths
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: