Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include functions from another file in my Perl script?

Tags:

include

perl

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.

like image 660
Zain Rizvi Avatar asked Nov 10 '09 23:11

Zain Rizvi


People also ask

How do you call a subroutine from another file in Perl?

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.

How do I import a Perl file into another Perl file?

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 .


2 Answers

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.

like image 56
daotoad Avatar answered Sep 28 '22 07:09

daotoad


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 with use are subject to earlier compile-time checks.
like image 21
martin clayton Avatar answered Sep 28 '22 06:09

martin clayton