fri*_*edo 48
可以像其他包符号一样导出常量.使用标准的Exporter模块,您可以从包中导出常量,如下所示:
package Foo;
use strict;
use warnings;
use base 'Exporter';
use constant CONST => 42;
our @EXPORT_OK = ('CONST');
1;
Run Code Online (Sandbox Code Playgroud)
然后,在客户端脚本(或其他模块)中
use Foo 'CONST';
print CONST;
Run Code Online (Sandbox Code Playgroud)
您可以使用%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' ] );
Run Code Online (Sandbox Code Playgroud)
然后你可以说
use Foo ':stooges';
print "$_\n" for LARRY, CURLY, MOE;
Run Code Online (Sandbox Code Playgroud)
mor*_*itz 25
常量只是具有空原型的子,因此它们可以像任何其他子一样导出.
# 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;
Run Code Online (Sandbox Code Playgroud)
Tan*_*lus 21
为了扩大在前面的答案,因为常量实际上只是替补,你可以也直接调用它们:
use Foo;
print Foo::BAR;
Run Code Online (Sandbox Code Playgroud)
小智 17
您可能想要考虑使用Readonly而不是常量.
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'
Run Code Online (Sandbox Code Playgroud)
要添加到技巧包中,因为常量只是一个子例程,您甚至可以将其称为类方法.
package Foo;
use constant PI => 3.14;
print Foo->PI;
Run Code Online (Sandbox Code Playgroud)
如果你有很多常量,这是一个很好的方法来偶尔获得它们而不必将它们全部导出.但是,与Perl 不同Foo::PI或导出时PI,Perl不会编译出来,Foo->PI因此会产生方法调用的成本(这可能无关紧要).