A more general approach for AppConfig

In my previous post about AppConfig I suggested an approach in order to read configuration options from a file, and override them with command-line options. It turns out that it works pretty well in the most common case (that is: only scalar variables are involved), but works really bad when list variables come into play.

The problem lies in the command line parsing happening two times, so while scalar variables are overwritten with the same value they had at the first pass, the list variables add the specified value again. Probably, not what you want. The fix is actually trivial:

# Reading configuration
# The first AppConfig object, we'll throw it away. We'll use it
# just to discover if there is a config file that we should read
# first, and then override config file options on the command line
my $config_file ;
  my $c        = AppConfig->new($ACparms,@config_vars) ;
  my $args     = [ @ARGV ] ;

  $c->args($args) ;
  $config_file = $c->get("config") ;

my $c = AppConfig->new($ACparms,@config_vars) ;

if (defined $config_file) {
  $c->file($config_file) ;

$c->args() ;

So basically, we parse the command line the first time inside a bare block, and just to find out if the config option was specified; that option will tell us if we have to parse a configuration file. Once the bare block is over, the AppConfig object ceases to exist, so when we get to the command line again, we are starting from scratch: no duplicated list values any more šŸ™‚


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.