This seems like a really simple question but somehow my Google-Fu failed me.
What's the syntax for including functions from other files in Perl? I'm looking for something like C's #include "blah.h"
I saw the option for using Perl modules, but that seems like it'll require a not-insignificant rewrite of my current code.
If you have subroutines defined in another file, you can load them in your program by using the use , do or require statement. A Perl subroutine can be generated at run-time by using the eval() function. You can call a subroutine directly or indirectly via a reference, a variable or an object.
require “path/to/filename.pl”; if the file is in the same folder as your main perl script you can just use it as KTotte has: require “filename.pl”; if you use “use” your file should be named with a .
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.
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:
require
are only loaded at run time, whereas packages loaded with use
are subject to earlier compile-time checks.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With