Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

use strict;
use warnings;

use Readonly;

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

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

like image 511
CROSP Avatar asked Aug 06 '15 17:08

CROSP


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

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});
}
like image 50
ikegami Avatar answered Oct 13 '22 16:10

ikegami