如何在 Perl 脚本中包含另一个文件中的函数?

2024-05-14

这似乎是一个非常简单的问题,但不知何故,我的 Google-Fu 失败了。

在 Perl 中包含其他文件中的函数的语法是什么?我正在寻找类似C的东西#include "blah.h"

我看到了使用 Perl 模块的选项,但这似乎需要对我当前的代码进行相当大的重写。


使用模块。查看perldoc perlmod http://perldoc.perl.org/perlmod.html and Exporter http://perldoc.perl.org/Exporter.html.

在文件 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 );

或者同时获得这两个函数:

use strict;
use warnings;

use Foo qw( export_me export_me_too );  # import listed items

export_me( 1 );
export_me_too( 1 );

您还可以导入包变量,但强烈建议不要这样做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Perl 脚本中包含另一个文件中的函数? 的相关文章

随机推荐