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.
The above answers all ignored the client part: How to import the module.
See the accepted answer here: How do I use a Perl module from a relative location?
Without the trick in this answer, you'll have plenty of trouble trying to get the module path right when you
use $mymodule;
Use a module. Check out perldoc perlmod and Exporter.
In file Foo.pm
In your main program:
Or to get both functions:
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
at the end of the file.
Here's a tiny sample:
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 withuse
are subject to earlier compile-time checks.I know the question specifically says "functions", but I get this post high up in search when I look for "perl include", and often times (like now) I want to include variables (in a simple way, without having to think about modules). And so I hope it's OK to post my example here (see also: Perl require and variables; in brief: use
require
, and make sure both "includer" and "includee" files declare the variable asour
):You really should look into perl modules however, for a quick hack you could always run "perl -P" which runs your perl script through the C pre-processor. That means you can do #include and friends....
Only a quick hack though, beware ;-)
I believe you are looking for the require or use keywords.