如何在我的 Perl 脚本中包含另一个文件中的函数? [英] How do I include functions from another file in my Perl script?
问题描述
这似乎是一个非常简单的问题,但不知何故我的 Google-Fu 让我失望了.
This seems like a really simple question but somehow my Google-Fu failed me.
在 Perl 中包含来自其他文件的函数的语法是什么?我正在寻找类似 C 的 #include "blah.h"
What's the syntax for including functions from other files in Perl? I'm looking for something like C's #include "blah.h"
我看到了使用 Perl 模块的选项,但这似乎需要对我当前的代码进行重大的重写.
I saw the option for using Perl modules, but that seems like it'll require a not-insignificant rewrite of my current code.
推荐答案
使用模块.查看 perldoc perlmod 和 出口商.
Use a module. Check out perldoc perlmod and Exporter.
在文件 Foo.pm 中
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;
在你的主程序中:
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 脚本中包含另一个文件中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!