Perl Moose - Loading values from config file etc.
I'm new to using Moose, but I was wondering how I can load values from a config file and then expose those values to the properties of my "config" object, where the attributes are the config names in the config file.
For example, a config file might contain:
server:mozilla.org
protocol:HTTP
So I want my config object to have a "server" attribute with "mozilla.org" and a protocol attribute with "HTTP".
I currently understand that I have to explicitly specify the attributes with
has 'server' => ( is => 'ro', isa => 'Str', default => 'mozilla.org' );
the type of entry in the Config.pm file.
How do I create them dynamically so that the config file can change without rewriting Config.pm every time it does it?
TIA!
source to share
This is not exactly what you asked for, but you can get an attribute config
containing a hash reference using BUILDARGS
to populate configuration information at build time. Assuming the lines in your config file are character-separated key-value pairs :
, something like this should work:
package My::Module;
use Moose;
has 'config'=>(isa=>'HashRef[Str]',is=>'rw',required=>1);
around BUILDARGS=>sub
{
my $orig=shift;
my $class=shift;
my $args=shift; #other arguments passed in (if any).
my %config_hash=();
open(my $read,"<","config_file") or confess $!;
while(<$read>)
{
chomp;
my @array=split /:/;
$config_hash{$array[0]}=$array[1];
}
close($read);
$args->{config}=\%config_hash;
return $class->$orig($args);
};
no Moose;
1;
With a little effort, it is also easy to get additional attributes to specify the name and path of the configuration file, along with a delimiter. They can be accessed inside BUILDARGS
, for example, $args->{config_file}
and $args->{config_delimiter}
.