如何使用Perl模块的常量? [英] How do I use constants from a Perl module?
问题描述
如果我在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?)
推荐答案
常量可以像其他程序包符号一样导出。使用标准出口商模块,您可以导出常量包裹如下:
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 "$_\n" for LARRY, CURLY, MOE;
这篇关于如何使用Perl模块的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!