How do I use constants from a Perl module?

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;

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.

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' ] );

Then you can say

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)