← Back to Perl Course | Chapter 8: Modules | Lesson 7 of 7

@INC and finding modules

Perl searches a list of directories, @INC, to find each module you load.

In this page:

  1. @INC and finding modules

@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

perl
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
Common Mistakes
  1. Naming the file differently from the package name
  2. Changing @INC at run time and then using use
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.