package My::App;
# ...
require Config::IniHash;
sub _configuration
{
my $self = shift;
unless ($self->{_configuration})
{
require Config::Find;
$self->{_config_name} = Config::Find->find(name => 'myapp',
mode => 'read');
if ($self->{_config_name} and -e $self->{_config_name})
{
$self->{_configuration} = $self->_default_configuration();
}
else
{
$self->{_configuration} = Config::IniHash->new($self->{_config_n
+ame});
}
}
$self->{_configuration};
}
sub _default_configuration
{
my $self = shift;
unless ($self->{_default_configuration})
{
# Config::IniHash docs don't say that it can take
# a glob, but the code does.
$self->{_default_configuration} =
Config::IniHash->new(\*DATA);
}
$self->{_default_configuration};
}
__DATA__
# defaults go here.
[section1]
key1=default value 1
key2=default value 2
[section2]
key1=default value 2-1
Because of the way that IniHash works, you may have to do something like this to use it:
my $value = $self->_configuration()->{section1}->{key1} ||
$self->_default_configuration()->{section1}->{key1};
Off the top of my head, I can't think how to combine them. Good luck!
PS - looking at the code I have this in, I'm using Config::Natural, so I have a sub that is "get_config", and I pass in the config var I want, and it does the work of checking the config file vs the DATA (defaults). |