如何使用 Perl 模块中的常量? [英] How do I use constants from a Perl module?

查看:23
本文介绍了如何使用 Perl 模块中的常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Perl 模块中定义了一个常量,我如何在主程序中使用该常量?(或者我如何在主程序中调用该常量?)

If I define a constant in a Perl module, how do I use that constant in my main program? (Or how do I call that constant in the main program?)

推荐答案

常量可以像其他包符号一样导出.使用标准的 Exporter 模块,您可以从像这样的包:

Constants can be exported just like other package symbols. Using the standard Exporter module, you can export constants from a package like this:

package Foo;
use strict;
use warnings;

use base 'Exporter';

use constant CONST => 42;

our @EXPORT_OK = ('CONST');

1;

然后,在客户端脚本(或其他模块)中

Then, in a client script (or other module)

use Foo 'CONST';
print CONST;

您可以使用 %EXPORT_TAGS 哈希(请参阅导出器文档)来定义可以使用单个导入参数导出的常量组.

You can use the %EXPORT_TAGS hash (see the Exporter documentation) to define groups of constants that can be exported with a single import argument.

更新:这里有一个示例,说明如果您有多个常量,如何使用 %EXPORT_TAGS 功能.

Update: Here's an example of how to use the %EXPORT_TAGS feature if you have multiple constants.

use constant LARRY => 42;
use constant CURLY => 43;
use constant MOE   => 44;

our @EXPORT_OK = ('LARRY', 'CURLY', 'MOE');
our %EXPORT_TAGS = ( stooges => [ 'LARRY', 'CURLY', 'MOE' ] );

那你可以说

use Foo ':stooges';
print "$_
" for LARRY, CURLY, MOE;

这篇关于如何使用 Perl 模块中的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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