5

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();
tekknolagi
  • 10,663
  • 24
  • 75
  • 119
  • Also: http://stackoverflow.com/questions/1712016/how-do-i-include-functions-from-another-file-in-my-perl-script – Alex Dec 15 '11 at 03:48
  • Possible duplicate of [How do I include functions from another file in my Perl script?](https://stackoverflow.com/questions/1712016/how-do-i-include-functions-from-another-file-in-my-perl-script) –  Apr 16 '18 at 04:07

2 Answers2

9

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.

Alex
  • 5,863
  • 2
  • 29
  • 46
6

Func.pm:

package Func;

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

sub test {
}

1;

File1.pl:

use Func;

test();
ikegami
  • 367,544
  • 15
  • 269
  • 518
Chris J
  • 1,375
  • 8
  • 20
  • Imported files must return a true value. – TLP Dec 15 '11 at 03:53
  • 2
    `use`/`require` is for modules, `do` otherwise. [details](http://stackoverflow.com/questions/6376006/what-is-the-difference-between-library-files-and-modules/6379109#6379109) – ikegami Dec 15 '11 at 04:25