There are other ways, but they all have severe issues. Modules are the way to go, and they don't have to be very complicated. Here is a basic template:
package Mod;
use strict;
use warnings;
use Exporter 'import';
#list of functions/package variables to automatically export
our @EXPORT = qw(
always_exported
);
#list of functions/package variables to export on request
our @EXPORT_OK = qw(
exported_on_request
also_exported_on_request
);
sub always_exported { print "Hi\n" }
sub exported_on_request { print "Hello\n" }
sub also_exported_on_request { print "hello world\n" }
1; #this 1; is required, see perldoc perlmod for details
Create a directory like /home/user/perllib
. Put that code in a file named Mod.pm
in that directory. You can use the module like this:
#!/usr/bin/perl
use strict;
use warnings;
#this line tells Perl where your custom modules are
use lib '/home/user/perllib';
use Mod qw/exported_on_request/;
always_exported();
exported_on_request();
Of course, you can name the file anything you want. It is good form to name the package the same as file. If you want to have ::
in the name of the package (like File::Find
) you will need to create subdirectories in /home/user/perllib
. Each ::
is equivalent to a /
, so My::Neat::Module
would go in the file /home/user/perllib/My/Neat/Module.pm
. You can read more about modules in perldoc perlmod
and more about Exporter
in perldoc Exporter