How do I include functions from another file in my Perl script?
Solution 1:
Use a module. Check out perldoc perlmod and Exporter.
In file Foo.pm
package Foo;
use strict;
use warnings;
use Exporter;
our @ISA= qw( Exporter );
# these CAN be exported.
our @EXPORT_OK = qw( export_me export_me_too );
# these are exported by default.
our @EXPORT = qw( export_me );
sub export_me {
# stuff
}
sub export_me_too {
# stuff
}
1;
In your main program:
use strict;
use warnings;
use Foo; # import default list of items.
export_me( 1 );
Or to get both functions:
use strict;
use warnings;
use Foo qw( export_me export_me_too ); # import listed items
export_me( 1 );
export_me_too( 1 );
You can also import package variables, but the practice is strongly discouraged.
Solution 2:
Perl require will do the job. You will need to ensure that any 'require'd files return truth by adding
1;
at the end of the file.
Here's a tiny sample:
$ cat m1.pl
use strict;
sub x { warn "aard"; }
1;
$ cat m2.pl
use strict;
require "m1.pl";
x();
$ perl m2.pl
aard at m1.pl line 2.
But migrate to modules as soon as you can.
EDIT
A few benefits of migrating code from scripts to modules:
- Without packages, everything occupies a single namespace, so you may hit a situation where two functions from separate files want the same name.
- A package allows you to expose some functions, but hide others. With no packages, all functions are visible.
- Files included with
require
are only loaded at run time, whereas packages loaded withuse
are subject to earlier compile-time checks.