Pascal2020 has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am using the Config::General module to be able to use a config file. But if a user does not set all options I want to be able to go back to a default value. How can I set these?

#!/usr/bin/env perl use Getopt::Long; use Config::General; $PROGNAME = "myscript"; # Get Options from commandline my $nodename; usage() if ( @ARGV < 1 or ! GetOptions( "nodename=s"=>\$nodename )); my $conf = new Config::General( -ConfigFile => $PROGNAME . '.conf', -ExtendedAccess => 1 ); &read_config; sub read_config { if ($conf->is_hash($nodename)) { $config = $conf->obj($nodename); } else { print "Critical error: No configuration list found for $nodena +me\n"; } }
The config look like this:
<server1> host = server1.domain.tld ssl = true port = 443 username = admin password = qwerty vhost = example </server1> <server2> host = server2.domain.tld ssl = false port = 2080 username = admin password = qwerty vhost = example </server2>

I want to check if a value exists to the config key and if not set a default one. But I cannot seem to figure out how.

So any pointers to a solution would be greatly appreciated!

Replies are listed 'Best First'.
Re: Config::General default config settings
by jeffa (Bishop) on Jun 30, 2014 at 13:52 UTC

    Parse the config file and change the values in the resulting data structure, let's say we want to default the username on the servers:

    use strict; use warnings; use Data::Dumper; use Config::General; my $conf = Config::General->new( -ConfigFile => \*DATA ); my %config = $conf->getall; $_->{username} ||= 'Pascal2020' for $config{server1}, $config{server2} +; print Dumper \%config; __DATA__ <server1> host = server1.domain.tld ssl = true port = 443 username = password = qwerty vhost = example </server1> <server2> host = server2.domain.tld ssl = false port = 2080 username = password = qwerty vhost = example </server2>

    There are many ways to do this, what did you try?

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Config::General default config settings
by thargas (Deacon) on Jul 02, 2014 at 11:20 UTC
    Have you tried the -DefaultConfig option?