如何在我的 Perl 脚本中包含另一个文件中的函数? [英] How do I include functions from another file in my Perl script?

查看:25
本文介绍了如何在我的 Perl 脚本中包含另一个文件中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个非常简单的问题,但不知何故我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆