What is the most efficient way to export all constants (Readonly variables) from a Perl module

I am looking for the most efficient and readable way to export all constants from my separate module, which is used only for storing constants.
For example,

use strict; use warnings; use Readonly; Readonly our $MY_CONSTANT1 => 'constant1'; Readonly our $MY_CONSTANT2 => 'constant2'; .... Readonly our $MY_CONSTANT20 => 'constant20'; 

So, I have many variables, and list them all inside @EXPORT = qw( MY_CONSTANT1.... );
It will be painful. Is there an elegant way to export all constants, in my case Readonly variables (force export all without using @EXPORT_OK).

+7
perl constants perl-module perl-exporter
source share
2 answers

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

Read-only variables using 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}); } 
+4
source share

If these are constants that may be required for interpolation into strings, etc., consider grouping related constants into a hash and making a hash constant using Const :: Fast . This reduces the pollution of the namespace, allows you to check all constants in a specific group, etc. For example, consider the READYSTATE enumeration values for the IE ReadyState . Instead of creating a separate variable or a 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 Bower's excellent CPAN module for constants .

+5
source share

All Articles