[ACCEPTED]-How do I use constants from a Perl module?-constants

Accepted answer
Score: 51

Constants can be exported just like other 9 package symbols. Using the standard Exporter module, you 8 can export constants from a package like 7 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 6 module)

use Foo 'CONST';
print CONST;

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

Update: Here's an example of how 2 to use the %EXPORT_TAGS feature if you have multiple 1 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' ] );

Then you can say

use Foo ':stooges';
print "$_\n" for LARRY, CURLY, MOE;
Score: 27

Constants are just subs with empty prototype, so 1 they can be exported like any other sub.

# 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;
Score: 22

To expand on the earlier answers, since 2 constants are really just subs, you can 1 also call them directly:

use Foo;
print Foo::BAR;
Score: 17

You might want to consider using Readonly instead 1 of constant.

Score: 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'

0

Score: 7

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

package Foo;
use constant PI => 3.14;

print Foo->PI;

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

More Related questions