To organize code in Perl, modules (packages) are used, which are formatted in separate files with a .pm extension.
use (at compile time) and require (at runtime) are applied.@INC — this is a list of directories where Perl looks for modules.Example of a module:
Foo.pm
package Foo; use strict; use warnings; sub say_hello { print "Hello from Foo! "; } 1;
Including and using:
use lib '.'; # Adds the current folder to @INC use Foo; Foo::say_hello(); # Outputs: Hello from Foo!
Main differences:
use imports the module at the beginning of the script execution and automatically calls the import method if there is one.require loads the module only on the first call.What is the difference between use and require? When should each operator be applied?
Answer:
use— acts at compile time, automatically callsimport(typically used for modules).require— acts at runtime, needed when the module name is unknown until execution or it is not always necessary to include it.
Story
In a large project, we included our own library via
require, forgetting that it uses exported functions. The used function was not exported becauserequiredoes not callimport. The result — symbol import did not work, and we had to call functions explicitly.
Story
When moving the module to a separate folder, we forgot to add the path to the folder via
use libor change the@INCvariable. The module was not found, and the script ended with an error, even though the file was in the correct place relative to the project.
Story
In an old application, we named the module with a lowercase letter but included it with an uppercase:
use foo;instead ofuse Foo;. Perl did not find the module, which impaired the functionality of critical parts of the application.