perl.gg

Custom Local Packages in Perl

Perl packages are an excellent way to organize code and create reusable modules. This post will guide you through creating custom packages in both the current folder and a subfolder, then loading them into your main program using FindBin for reliable path resolution.

Creating a Package in the Current Folder

Let's start by creating a simple package called "MyUtils" in the same folder as our main script.

Create a file named "MyUtils.pm" with the following content:

This package contains two subroutines: greet and square.

Creating a Package in a Subfolder

Now, let's create a package in a subfolder. First, create a directory called "lib" in your project folder.

Inside the "lib" folder, create a file named "MathOps.pm" with this content:

Using Both Packages in Your Main Script

Create your main script "main.pl" in the project root directory:

Run the script, and you should see:

Importing Functions Without Package Names

You can also import functions from a package to use them without the package name prefix. Here's how to modify "MyUtils.pm":

Now update your "main.pl" script:

Run the script, and you'll see:

Key Points:

  1. Package files should have a .pm extension.

  2. The package name should match the filename (e.g., "MyUtils.pm" contains package MyUtils;).

  3. Always end your package file with 1; to ensure it returns a true value.

  4. Use use FindBin qw($RealBin); and use lib ($RealBin, "$RealBin/lib"); to add directories to Perl's module search path reliably.

  5. Call package functions using the PackageName::function_name() syntax.

  6. To import functions for use without the package name prefix, use the Exporter module and specify which functions to export.

By following these steps and using FindBin, you can create and use custom Perl packages both in the current folder and subfolders with reliable path resolution. This approach helps organize your code and makes it more maintainable and reusable.