Perl Language Packages and modules Using a module inside a directory

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

use lib 'includes';
use MySuperCoolModule;

use lib 'includes'; adds the relative directory includes/ as another module search path in @INC. So assume that you have a module file MySyperCoolModule.pm inside includes/, which contains:

package MySuperCoolModule;

If you want, you can group as many modules of your own inside a single directory and make them findable with one use lib statement.

At this point, using the subroutines in the module will require prefixing the subroutine name with the package name:

MySuperCoolModule::SuperCoolSub_1("Super Cool String");

To be able to use the subroutines without the prefix, you need to export the subroutine names so that they are recognised by the program calling them. Exporting can be set up to be automatic, thus:

package MySuperCoolModule;
use base 'Exporter';
our @EXPORT = ('SuperCoolSub_1', 'SuperCoolSub_2');

Then in the file that uses the module, those subroutines will be automatically available:

use MySuperCoolModule;
SuperCoolSub_1("Super Cool String");

Or you can set up the module to conditionally export subroutines, thus:

package MySuperCoolModule;
use base 'Exporter';
our @EXPORT_OK = ('SuperCoolSub_1', 'SuperCoolSub_2');

In which case, you need to explicitly request the desired subroutines to be exported in the script that uses the module:

use MySuperCoolModule 'SuperCoolSub_1';
SuperCoolSub_1("Super Cool String");


Got any Perl Language Question?