tekknolagi
tekknolagi

Reputation: 11012

"include"-esque function for Perl

I have a function that I would like to define in two different Perl scripts, but dislike having to edit both. Is there a way I can include it (like in PHP) from an external file?

FUNC FILE:

sub test {

}

FILE 1:

include func_file;
foo();
bar();
test();

FILE 2:

include func_file;
blah();
test();

Upvotes: 5

Views: 170

Answers (2)

Chris J
Chris J

Reputation: 1375

Func.pm:

package Func;

use Exporter qw( import );
our @EXPORT = qw( test );

sub test {
}

1;

File1.pl:

use Func;

test();

Upvotes: 6

Alex
Alex

Reputation: 5893

To answer the question narrowly:

Yes, you can include a file by using the require('filename') function.

To answer the question generally:

Perl has a complete mechanism for defining and exporting functions through its package mechanism. This is described in perlmod. You should really use this mechanism, as you can eventually package up the module into a CPAN module, and make it available for others, or simply easy to install on other systems yourself.

Upvotes: 9

Related Questions