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:


So I want my config object to have a "server" attribute with "" 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 => '' );


the type of entry in the file.

How do I create them dynamically so that the config file can change without rewriting every time it does it?



source to share

2 answers

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 $!;
    my @array=split /:/;


  return $class->$orig($args);

no Moose;


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}




This obvious idea has been implemented several times already.

Also see

which map command line options to attributes that you most likely want as well.



All Articles