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.
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:
xxxxxxxxxxpackage ;
use ;use ;
sub { my $name = shift; return "Hello, $name!";}
sub { my $num = shift; return $num * $num;}
1;This package contains two subroutines: greet and square.
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:
xxxxxxxxxxpackage ;
use ;use ;
sub { my ($a, $b) = @_; return $a + $b;}
sub { my ($a, $b) = @_; return $a * $b;}
1;Create your main script "main.pl" in the project root directory:
xxxxxxxxxx#!/usr/bin/perl
use ;use ;use qw($RealBin);use ($RealBin, "$RealBin/lib"); # Add both directories to module search pathuse ;use ;
my $greeting = ::("Bob");print $greeting . "\n";
my $squared = ::(5);print "5 squared is: $squared\n";
my $sum = ::(3, 4);print "3 + 4 = $sum\n";
my $product = ::(3, 4);print "3 * 4 = $product\n";Run the script, and you should see:
xxxxxxxxxxHello, Bob!5 squared is: 253 + 4 = 73 * 4 = 12
You can also import functions from a package to use them without the package name prefix. Here's how to modify "MyUtils.pm":
xxxxxxxxxxpackage ;
use ;use ;use qw(import);
our @EXPORT_OK = qw(greet square);our %EXPORT_TAGS = ( => [@EXPORT_OK]);
sub { my $name = shift; return "Hello, $name!";}
sub { my $num = shift; return $num * $num;}
1;Now update your "main.pl" script:
xxxxxxxxxx#!/usr/bin/perl
use ;use ;use qw($RealBin);use ($RealBin, "$RealBin/lib");use qw(greet square); # Import specific functions
my $greeting = ("Charlie"); # No package name neededprint $greeting . "\n";
my $result = (6); # No package name neededprint "6 squared is: $result\n";Run the script, and you'll see:
xxxxxxxxxxHello, Charlie!6 squared is: 36
Package files should have a .pm extension.
The package name should match the filename (e.g., "MyUtils.pm" contains package MyUtils;).
Always end your package file with 1; to ensure it returns a true value.
Use use FindBin qw($RealBin); and use lib ($RealBin, "$RealBin/lib"); to add directories to Perl's module search path reliably.
Call package functions using the PackageName::function_name() syntax.
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.