43

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

4

6 回答 6

49

常量可以像其他包符号一样导出。使用标准的Exporter模块,您可以从包中导出常量,如下所示:

package Foo;
use strict;
use warnings;

use base 'Exporter';

use constant CONST => 42;

our @EXPORT_OK = ('CONST');

1;

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

use Foo 'CONST';
print CONST;

您可以使用%EXPORT_TAGS散列(参见 Exporter 文档)来定义可以使用单个导入参数导出的常量组。

%EXPORT_TAGS更新:如果您有多个常量,这是一个如何使用该功能的示例。

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;
于 2008-10-10T21:10:39.090 回答
27

常量只是具有空原型的子,因此它们可以像任何其他子一样导出。

# file Foo.pm
package Foo;
use constant BAR => 123;
use Exporter qw(import);
our @EXPORT_OK = qw(BAR);


# file main.pl:
use Foo qw(BAR);
print BAR;
于 2008-10-10T21:11:36.670 回答
22

为了扩展之前的答案,由于常量实际上只是子类,您也可以直接调用它们:

use Foo;
print Foo::BAR;
于 2008-10-10T21:21:01.160 回答
17

您可能需要考虑使用Readonly而不是常量。

于 2008-10-11T10:22:16.120 回答
8
package Foo;
use Readonly;
Readonly my  $C1 => 'const1';
Readonly our $C2 => 'const2';
sub get_c1 { return $C1 }
1;

perl -MFoo -e 'print "$_\n" for Foo->get_c1, $Foo::C2'
于 2008-10-12T20:04:02.170 回答
7

To add to the bag of tricks, since a constant is just a subroutine you can even call it as a class method.

package Foo;
use constant PI => 3.14;

print Foo->PI;

If you have lots of constants it's a nice way to get at the occasional one without having to export them all. However, unlike Foo::PI or exporting PI, Perl will not compile out Foo->PI so you incur the cost of a method call (which probably doesn't matter).

于 2008-10-18T09:07:56.143 回答