in reply to [General] Non-Specific Options Question

G'day arblargan,

There's probably some options you'll want to hard-code such as '--version' and '--help'. These typically run some very small part of the code and then terminate: the main application wouldn't be run. They are options without values whose operations you wouldn't want your users to change; although, you may allow some output modifications with options like '--verbose' and '--full'.

There may be some default values that you might want to hard-code or place in some sort of master configuration file. These could be overridden by user choices in a user configuration file.

You may want to allow users to set up options in an environment variable. These might be specific to a client, project, and so on: not general enough for a config file but a nuisance to restate for every run.

Then you might want command line options: items that users want to change on a run-by-run basis.

If your application is interactive, perhaps users can change options in mid-run.

I see ++Discipulus has provided some information on config files. I won't elaborate on that.

Here's some code that allows users to change starting settings with values from an environment variable; and then to override those with command line options.

#!/usr/bin/env perl -l use strict; use warnings; use Getopt::Long 'GetOptionsFromString'; my ($x, $y, $z) = qw{42 fred 1.0}; my %opts = ('x=i', \$x, 'y=s', \$y, 'z=f', \$z); print 'Option starting values:'; print "Options: x[$x] y[$y] z[$z]"; if (exists $ENV{USER_OPTS}) { GetOptionsFromString($ENV{USER_OPTS}, %opts); print 'After environment variable options processed:'; print "Options: x[$x] y[$y] z[$z]"; } if (@ARGV) { GetOptions(%opts); print 'After command line options processed:'; print "Options: x[$x] y[$y] z[$z]"; }

Here's a few sample runs to show that in action.

$ pm_1196515_option_processing.pl Option starting values: Options: x[42] y[fred] z[1.0] $ export USER_OPTS='-z 1.5' $ pm_1196515_option_processing.pl Option starting values: Options: x[42] y[fred] z[1.0] After environment variable options processed: Options: x[42] y[fred] z[1.5] $ pm_1196515_option_processing.pl -x 21 Option starting values: Options: x[42] y[fred] z[1.0] After environment variable options processed: Options: x[42] y[fred] z[1.5] After command line options processed: Options: x[21] y[fred] z[1.5] $ pm_1196515_option_processing.pl -y wilma -z 3.4 Option starting values: Options: x[42] y[fred] z[1.0] After environment variable options processed: Options: x[42] y[fred] z[1.5] After command line options processed: Options: x[42] y[wilma] z[3.4]

If you want to give users the ability to change options in mid-run, here's some code I posted a few months ago to do that: "Re: How to process Getopt::Long from STDIN".

— Ken