What is the most efficient way to export all constants (Readonly variables) from Perl module
Actual constants:
use constant qw( );
use Exporter qw( import );
our @EXPORT_OK;
my %constants = (
MY_CONSTANT1 => 'constant1',
MY_CONSTANT2 => 'constant2',
...
);
push @EXPORT_OK, keys(%constants);
constant->import(\%constants);
Variables made read-only with Readonly:
use Exporter qw( import );
use Readonly qw( Readonly );
our @EXPORT_OK;
my %constants = (
MY_CONSTANT1 => 'constant1',
MY_CONSTANT2 => 'constant2',
#...
);
for my $name (keys(%constants)) {
push @EXPORT_OK, '$'.$name;
no strict 'refs';
no warnings 'once';
Readonly($$name, $constants{$name});
}
If these are constants which may need to to be interpolated into strings etc, consider grouping related constants into a hash, and making the hash constant using Const::Fast. This reduces namespace pollution, allows you to inspect all constants in a specific group etc. For example, consider the READYSTATE enumeration values for IE's ReadyState
property. Instead of creating a separate variable, or separate constant function for each value, you could group them in a hash:
package My::Enum;
use strict;
use warnings;
use Exporter qw( import );
our @EXPORT_OK = qw( %READYSTATE );
use Const::Fast;
const our %READYSTATE => (
UNINITIALIZED => 0,
LOADING => 1,
LOADED => 2,
INTERACTIVE => 3,
COMPLETE => 4,
);
__PACKAGE__;
__END__
And, then, you can intuitively use them as in:
use strict;
use warnings;
use My::Enum qw( %READYSTATE );
for my $state (sort { $READYSTATE{$a} <=> $READYSTATE{$b} } keys %READYSTATE) {
print "READYSTATE_$state is $READYSTATE{$state}\n";
}
See also Neil Bowers' excellent review on 'CPAN modules for defining constants'.