.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "App::Options 3pm" .TH App::Options 3pm "2010-10-12" "perl v5.20.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" App::Options \- Combine command line options, environment vars, and option file values (for program configuration) .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& #!/usr/bin/perl \-w \& use strict; \& \& use App::Options; # reads option values into %App::options by default \& \& # do something with the options (in %App::options) \& use DBI; \& $dsn = "dbi:mysql:database=$App::options{dbname}"; \& $dbh = DBI\->connect($dsn, $App::options{dbuser}, $App::options{dbpass}); \& ... \& \& Get help from the command line (assuming program is named "prog") ... \& \& prog \-? \& prog \-\-help \& \& Option values may be provided on the command line, in environment \& variables, and option files. (i.e. $ENV{APP_DBNAME} would set \& the value of %App::options{dbname} by default.) \& \& The "dbname" and other options could also be set in one of the \& following configuration files \& \& /etc/app/policy.conf \& $HOME/.app/prog.conf \& $HOME/.app/app.conf \& $PROGDIR/prog.conf \& $PROGDIR/app.conf \& $PREFIX/etc/app/prog.conf \& $PREFIX/etc/app/app.conf \& /etc/app/app.conf \& \& with a file format like \& \& [prog] \& dbname = prod \& dbuser = scott \& dbpass = tiger \& \& See below for a more detailed explanation of these and other \& advanced features. .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" App::Options combines command-line arguments, environment variables, option files, and program defaults to produce a hash of option values. .SH "RELATION TO OTHER CONFIGURATION/OPTION PARSING MODULES" .IX Header "RELATION TO OTHER CONFIGURATION/OPTION PARSING MODULES" A number of modules are posted on \s-1CPAN\s0 which do command-line processing. .PP .Vb 1 \& http://search.cpan.org/modlist/Option_Parameter_Config_Processing .Ve .PP App::Options is different than most of the Getopt::* modules because it integrates the processing of command line options, environment variables, and config files. .PP Furthermore, its special treatment of the \*(L"perlinc\*(R" option facilitates the inclusion (\*(L"use\*(R") of application-specific perl modules from special places to enable the installation of multiple versions of an application on the same system (i.e. /usr/myproduct/version). .PP The description of the AppConfig distribution sounds similar to what is described here. However, the following are some key differences. .PP .Vb 3 \& * App::Options does its option processing in the BEGIN block. \& This allows for the @INC variable to be modified in time \& for subsequent "use" and "require" statements. \& \& * App::Options "sections" (i.e. "[cleanup]") are conditional. \& It is conditional in App::Options, allowing you to use one \& set of option files to configure an entire suite of programs \& and scripts. In AppConfig, the section name is simply a \& prefix which gets prepended to subsequest option names. \& \& * App::Options consults a cascading set of option files. \& These files include those which are system global, project \& global, and user private. This allows for system \& administrators, project developers, and individual \& users to all have complementary roles in defining \& the configuration values. \& \& * App::Options is not a toolkit but a standardized way of \& doing option processing. With AppConfig, you still have \& to decide where to put config files, and you still have to \& code the "\-\-help" feature. With App::Options, you simply \& "use App::Options;" and all the hard work is done. \& Advanced options can be added later as necessary as args \& to the "use App::Options;" statement. .Ve .PP App::Options is also the easiest command-line processing system that I have found anywhere. It then provides a smooth transition to more advanced features only as they are needed. Every single quick and dirty script I ever write from now on can afford to use App::Options. .PP The documentation of App::Options takes three forms below. .PP .Vb 3 \& API Reference \- describing the API (methods, args) \& Logic Flow \- describing the order and logic of processing \& Usage Tutorial \- describing how to use the API in practical situations .Ve .SH "RELATION TO THE P5EE PROJECT" .IX Header "RELATION TO THE P5EE PROJECT" App::Options was motivated by and supports the P5EE/App\-Context variant of the Perl 5 Enterprise Environment (P5EE). However, App::Options has no dependency on any other module in the P5EE project, and it is very useful without any knowledge or use of other elements of the P5EE project. .PP See the P5EE web sites for more information on the P5EE project. .PP .Vb 1 \& http://www.officevision.com/pub/p5ee/index.html .Ve .SH "API REFERENCE: Methods" .IX Header "API REFERENCE: Methods" .SS "\fIinit()\fP" .IX Subsection "init()" .Vb 10 \& * Signature: App::Options\->init(); \& * Signature: App::Options\->init(%named); \& * Signature: App::Options\->init($myvalues); \& * Signature: App::Options\->init($myvalues, %named); \& (NOTE: %named represents a list of name/value pairs used as named args. \& Params listed below without a $ are named args.) \& * Param: $myvalues HASH \& specify a hash reference other than %App::options to put \& configuration values in. \& * Param: values HASH \& specify a hash reference other than %App::options to put \& configuration values in. \& * Param: options ARRAY \& specify a limited, ordered list of options to be displayed \& when the "\-\-help" or "\-?" options are invoked \& * Param: option HASH \& specify additional attributes of any of \& the various options to the program (see below) \& * Param: no_cmd_args \& do not process command line arguments \& * Param: no_env_vars \& do not read environment variables \& * Param: no_option_file \& do not read in the option file(s) \& * Param: print_usage \& provide an alternate print_usage() function \& * Return: void \& * Throws: "App::Options\->init(): must have an even number of vars/values for named args" \& * Throws: "App::Options\->init(): \*(Aqvalues\*(Aq arg must be a hash reference" \& * Throws: "App::Options\->init(): \*(Aqoption\*(Aq arg must be a hash reference" \& * Throws: "App::Options\->init(): \*(Aqoptions\*(Aq arg must be an array reference" \& * Since: 0.60 \& \& Sample Usage: (normal) \& \& use App::Options; # invokes init() automatically via import() \& \& This is functionally equivalent to the following, but that\*(Aqs not \& near as nice to write at the top of your programs. \& \& BEGIN { \& use App::Options qw(:none); # import() does not call init() \& App::Options\->init(); # we call init() manually \& } \& \& Or we could have used a more full\-featured version ... \& \& use App::Options ( \& values => \e%MyPackage::options, \& options => [ "option_file", "prefix", "app", \& "perlinc", "debug_options", "import", ], \& option => { \& option_file => { default => "~/.app/app.conf" }, # set default \& app => { default => "app", type => "string" }, # default & type \& prefix => { type => "string", required => 1; env => "PREFIX" }, \& perlinc => undef, # no default \& debug_options => { type => "int" }, \& import => { type => "string" }, \& flush_imports => 1, \& }, \& no_cmd_args => 1, \& no_env_vars => 1, \& no_option_file => 1, \& print_usage => sub { my ($values, $init_args) = @_; print "Use it right!\en"; }, \& ); .Ve .PP The \fIinit()\fR method is usually called during the \fIimport()\fR operation when the normal usage (\*(L"use App::Options;\*(R") is invoked. .PP The \fIinit()\fR method reads the command line args (@ARGV), then finds an options file, and loads it, all in a way which can be done in a \s-1BEGIN\s0 block (minimal dependencies). This is important to be able to modify the \f(CW@INC\fR array so that normal \*(L"use\*(R" and \*(L"require\*(R" statements will work with the configured \f(CW@INC\fR path. .PP The following named arguments are understood by the \fIinit()\fR method. .PP .Vb 10 \& values \- specify a hash reference other than %App::options to \& put option values in. \& options \- specify a limited, ordered list of options to be \& displayed when the "\-\-help" or "\-?" options are invoked \& option \- specify optional additional information about any of \& the various options to the program (see below) \& no_cmd_args \- do not process command line arguments \& no_env_vars \- do not read environment variables \& no_option_file \- do not read in the option file \& show_all \- force showing all options in "\-\-help" even when \& "options" list specified \& print_usage \- provide an alternate print_usage() function \& args_description \- provide descriptive text for what the args \& of the program are (command line args after the options). \& This is printed in the usage page (\-\-help or \-?). \& By default, it is simply "[args]". .Ve .PP The additional information that can be specified about any individual option variable using the \*(L"option\*(R" arg above is as follows. .PP .Vb 10 \& default \- the default value if none supplied on the command \& line, in an environment variable, or in an option file \& required \- the program will not run unless a value is provided \& for this option \& type \- if a value is provided, the program will not run unless \& the value matches the type ("string", "integer", "float", \& "boolean", "date", "time", "datetime", "/regexp/"). \& env \- a list of semicolon\-separated environment variable names \& to be used to find the value instead of "APP_{VARNAME}". \& description \- printed next to the option in the "usage" page \& secure \- identifies an option as being "secure" (i.e. a password) \& and that it should never be printed in plain text in a help \& message (\-?). All options which end in "pass", "passwd", or \& "password" are also assumed to be secure unless a secure => 0 \& setting exists. If the value of the "secure" attribute is greater \& than 1, a heightened security level is enforced: 2=ensure that \& the value can never be supplied on a command line or from the \& environment but only from a file that only the user running the \& program has read/write access to. This value will also never be \& read from the environment or the command line because these are \& visible to other users. If the security_policy_level variable \& is set, any true value for the "secure" attribute will result in \& the value being set to the "security_policy_level" value. \& value_description \- printed within angle brackets ("<>") in the \& "usage" page as the description of the option value \& (i.e. \-\-option_name=) .Ve .PP The \fIinit()\fR method stores command line options and option file values all in the global \f(CW%App::options\fR hash (unless the \&\*(L"values\*(R" argument specifies another reference to a hash to use). .PP The special options are as follows. .PP .Vb 2 \& option_file \- specifies the exact file name of the option file to be \& used (i.e. "app \-\-option_file=/path/to/app.conf"). \& \& app \- specifies the tag that will be used when searching for \& an option file. (i.e. "app \-\-app=myapp" will search for "myapp.conf" \& before it searches for "app.conf") \& "app" is automatically set with the stem of the program file that \& was run (or the first part of PATH_INFO) if it is not supplied at \& the outset as an argument. \& \& prefix \- This represents the base directory of the software \& installation (i.e. "/usr/myproduct/1.3.12"). If it is not \& set explicitly, it is detected from the following places: \& 1. PREFIX environment variable \& 2. the real path of the program with /bin or /cgi\-bin stripped \& 3. /usr/local (or whatever "prefix" perl was compiled with) \& If it is autodetected from one of those three places, that is \& only provisional, in order to find the "option_file". The "prefix" \& variable should be set authoritatively in the "option_file" if it \& is desired to be in the $values structure. \& \& perlinc \- a path of directories to prepend to the @INC search path. \& This list of directories is separated by any combination of \& [,; ] characters. \& \& debug_options \- if this is set, a variety of debug information is \& printed out during the option processing. This helps in debugging \& which option files are being used and what the resulting variable \& values are. The following numeric values are defined. \& \& 1 = print the basic steps of option processing \& 2 = print each option file searched, final values, and resulting @INC \& 3 = print each value as it is set in the option hash \& 4 = print overrides from ENV and variable substitutions \& 5 = print each line of each file with exclude_section indicator \& 6 = print option file section tags, condition evaluation, and \& each value found (even if it is not set in the final values) \& 7 = print final values \& \& import \- a list of additional option files to be processed. \& An imported file goes on the head of the queue of files to be \& processed. \& \& hostname \- the hostname as returned by the hostname() function \& provided by Sys::Hostname (may or may not include domain \& qualifiers as a fully qualified domain name). \& \& host \- same as hostname, but with any trailing domain name removed. \& (everything after the first ".") \& \& flush_imports \- flush all pending imported option files. \& \& security_policy_level \- When set, this enforces that whenever secure \& attributes are applied, they are set to the same level. When set \& 0, all of the security features are disabled (passwords can be \& viewed with "\-\-security_policy_level=0 \-\-help"). When set to 2, \& all secure options can only be read from files which do not have \& read/write permission by any other user except the one running the \& program. .Ve .SH "LOGIC FLOW: OPTION PROCESSING DETAILS" .IX Header "LOGIC FLOW: OPTION PROCESSING DETAILS" Basic Concept \- By calling App::Options\->\fIinit()\fR, your program parses the command line, environment variables, and option files, and puts var/value pairs into a global option hash, \f(CW%App::options\fR. Just include the following at the top of your program in order to imbue it with many valuable option-setting capabilities. .PP .Vb 1 \& use App::Options; .Ve .PP When you \*(L"use\*(R" the App::Options module, the \fIimport()\fR method is called automatically. This calls the \fIinit()\fR method, passing along all of its parameters. .PP One of the args to \fIinit()\fR is the \*(L"values\*(R" arg, which allows for a different hash to be specified as the target of all option variables and values. .PP .Vb 1 \& use App::Options (values => \e%Mymodule::opts); .Ve .PP Throughout the following description of option processing, the \f(CW%App::options\fR hash may be referred to as the \*(L"options hash\*(R". However it will be understood that some other hash (as specified by the \*(L"values\*(R" arg) may actually be used. .SS "Command Line Arguments" .IX Subsection "Command Line Arguments" Unless the \*(L"no_cmd_args\*(R" arg is specified to \fIinit()\fR, the first source of option values is the command line. .PP Each command line argument that begins with a \*(L"\-\*(R" or a \*(L"\-\-\*(R" is considered to be an option. It may take any form such as .PP .Vb 5 \& \-\-verbose # long option, no arg \& \-\-verbose=5 # long option, with arg \& \-\-city=ATL # long option, with arg \& \-x # short option, no arg \& \-t=12:30 # short option, with arg .Ve .PP All detected options are shifted out of \f(CW@ARGV\fR and the values are set in the options hash (%App::options). Options without args are understood to have a value of \*(L"1\*(R". So \*(L"\-\-verbose\*(R" is identical to \*(L"\-\-verbose=1\*(R". .PP Naturally, the \*(L"\-\-\*(R" option terminates command line option processing. .SS "Command Line Argument Variable Substitution" .IX Subsection "Command Line Argument Variable Substitution" Any value which includes a variable undergoes variable substitution before it is placed in the option hash. i.e. .PP .Vb 1 \& logdir = ${prefix}/log .Ve .PP This line will be expanded properly. (Of course, the variable and its value should be already set in the option hash.) .PP Variable substitution is also performed to interpolate values from the environment. .PP .Vb 1 \& port = $ENV{HTTP_PORT} .Ve .ie n .SS "Special Option ""app""" .el .SS "Special Option ``app''" .IX Subsection "Special Option app" If the special option, \*(L"app\*(R", was not given on the command line, it is initialized. This option is useful for including or excluding different sections of the option files. .PP To handle the special case that the program is running in a \s-1CGI\s0 environment, the \s-1PATH_INFO\s0 variable is checked first. The first segment of the \s-1PATH_INFO\s0 is stripped off, and that becomes the value of the \*(L"app\*(R" option. .PP Otherwise, the stem of the program name becomes the value of the \&\*(L"app\*(R" option. The stem is the program name without any trailing extension (i.e. \*(L".exe\*(R", \*(L".pl\*(R", etc.). .SS "The Program Directory" .IX Subsection "The Program Directory" One of the places that will be searched for option files is the directory in which the program exists on the file system. This directory is known internally as \*(L"$prog_dir\*(R". .ie n .SS "Special Option ""prefix""" .el .SS "Special Option ``prefix''" .IX Subsection "Special Option prefix" The special option, \*(L"prefix\*(R", represents the root directory of the software installation. On a Unix system, a suite of software might by installed at \*(L"/usr/myproduct/thisversion\*(R", and that would be the \*(L"prefix\*(R". Under this directory, you would expect to find the \&\*(L"src\*(R", \*(L"bin\*(R", \*(L"lib\*(R", and \*(L"etc\*(R" directories, as well as perhaps \&\*(L"cgi-bin\*(R", \*(L"htdocs\*(R", and others. .PP If the \*(L"prefix\*(R" option is not specified on the command line, the \f(CW$PREFIX\fR environment variable is used. .PP If that is not set, the \f(CW$prog_dir\fR with the trailing \*(L"/bin\*(R" or \&\*(L"/cgi\-bin\*(R" stripped off is used. .SS "Option Files" .IX Subsection "Option Files" Unless the \*(L"no_option_file\*(R" arg is specified to \fIinit()\fR, the next source of option values is the option files. .PP By default, a cascading set of option files are all consulted to allow individual users to specify values that override the normal values for certain programs. Furthermore, the values for individual programs can override the values configured generally system-wide. .PP The resulting value for an option variable comes from the first place that it is ever seen. Subsequent mentions of the option variable within the same or other option files will be ignored. .PP The following files are consulted in order. .PP .Vb 7 \& $ENV{HOME}/.app/$app.conf \& $ENV{HOME}/.app/app.conf \& $prog_dir/$app.conf \& $prog_dir/app.conf \& $prefix/etc/app/$app.conf \& $prefix/etc/app/app.conf \& /etc/app/app.conf .Ve .PP Thus, a system administrator might set up the \f(CW$prefix\fR/etc/app/app.conf file with system-wide defaults. All option configuration could be done in this single file, separating the relevant variables into different sections for each different program to be configured. .PP However, if the administrator decided that there were too many parameters for a single program such that it cluttered this file, he might put the option values for that program into the \f(CW$prefix\fR/etc/app/$app.conf file. This distinction is a matter of preference, as both methods are equally functional. .PP A program developer may decide to override some of the system-wide option values for everyone by putting option files in the program's own directory. .PP Furthermore, a user may decide to override some of the resulting option values by putting some option files in the appropriate place under his home directory. .PP This separation of config files also allows for secure information (such as database passwords) to be required to be provided in the user's own (secured) option files rather than in read-only system-wide option files. .PP Specifying the \*(L"\-\-debug_options\*(R" option on the command line will assist in figuring out which files App::Options is looking at. .SS "Option File Format" .IX Subsection "Option File Format" In general an option file takes the form of lines with \*(L"var = value\*(R". .PP .Vb 3 \& dbname = prod # this is the production database \& dbuser = scott \& dbpass = tiger .Ve .PP Trailing comments (preceded by a \*(L"#\*(R") are trimmed off. Spaces before and after the variable, and before and after the value are all trimmed off. Then enclosing double-quotes (\*(L") are trimmed off. Variables can be any of the characters in [a\-zA\-Z0\-9_.\-]. Values can be any printable characters or the empty string. Any lines which aren't recognizable as \*(R"var = value" lines or section headers (see below) are ignored. .PP If certain variables should be set only for certain programs (or under certain other conditions), section headers may be introduced. The special section headers \*(L"[\s-1ALL\s0]\*(R" and \*(L"[]\*(R" specify the end of a conditional section and the resumption of unconditional option variables. .PP .Vb 6 \& [progtest] \& dbname = test # this is the test database \& [ALL] \& dbname = prod # this is the production database \& dbuser = scott \& dbpass = tiger .Ve .PP In this case, the \*(L"progtest\*(R" program will get \*(L"dbname = test\*(R" while all other programs will get \*(L"dbname = prod\*(R". .PP Note that you would not get the desired results if the \*(L"dbname = prod\*(R" statement was above the \*(L"[progtest]\*(R" header. Once an option variable is set, no other occurrence of that variable in any option file will override it. .PP For the special case where you want to specify a section for only one variable as above, the following shortcut is provided. .PP .Vb 4 \& [progtest] dbname = test # this is the test database \& dbname = prod # this is the production database \& dbuser = scott \& dbpass = tiger .Ve .PP The \*(L"[progtest]\*(R" section header applied for only the single line. .PP Furthermore, if it were desired to make this override for all programs containing \*(L"test\*(R" in them, you would use the following syntax. .PP .Vb 4 \& [/test/] dbname = test # this is the test database \& dbname = prod # this is the production database \& dbuser = scott \& dbpass = tiger .Ve .PP The \*(L"[/test/]\*(R" section header tested the \*(L"app\*(R" option using an arbitrary regular expression. .PP The section headers can create a condition for inclusion based on any of the variables currently in the option hash. In fact, \*(L"[progtest]\*(R" is just a synonym for \&\*(L"[app=progtest]\*(R" and \*(L"[/test/]\*(R" is a synonym for \*(L"[app=/test/]\*(R". .PP If, for instance, the usernames and passwords were different for the different databases, you might have the following. .PP .Vb 8 \& [/test/] dbname = test # progs with "test" go to test database \& dbname = prod # other progs go to the production database \& [dbname=test] # progs \& dbuser = scott \& dbpass = tiger \& [dbname=prod] \& dbuser = mike \& dbpass = leopard .Ve .PP The conditions created by a section header may be the result of more than a single condition. .PP .Vb 8 \& [dbname=test;dbuser=scott] \& dbpass = tiger \& [dbname=test;dbuser=ken] \& dbpass = ocelot \& [dbname=prod;dbuser=scott] \& dbpass = tiger62 \& [dbname=prod;dbuser=ken] \& dbpass = 3.ocelot_ .Ve .PP Any number of conditions can be included with semicolons separating them. .PP Each time a variable/value pair is found in an option file, it is only included in the option hash if that variable is currently not defined in the option hash. Therefore, option files never override command line parameters. .SS "Option Environment Variables and Variable Substitution" .IX Subsection "Option Environment Variables and Variable Substitution" For each variable/value pair that is to be inserted into the option hash from the option files, the corresponding environment variables are searched to see if they are defined. The environment always overrides an option file value. (If the \&\*(L"no_env_vars\*(R" arg was given to the \fIinit()\fR method, this whole step of checking the environment is skipped.) .PP By default, the environment variable for an option variable named \&\*(L"dbuser\*(R" would be \*(L"\s-1APP_DBUSER\*(R". \s0 However, if the \*(L"env\*(R" attribute of the \*(L"dbuser\*(R" option is set, a different environment variable may be checked instead (see the Tutorial below for examples). .PP After checking the environment for override values, any value which includes a variable undergoes variable substitution before it is placed in the option hash. .SS "Setting Environment Variables from Option Files" .IX Subsection "Setting Environment Variables from Option Files" Any variable of the form \*(L"ENV{\s-1XYZ\s0}\*(R" will set the variable \s-1XYZ\s0 in the environment rather than in the options hash. Thus, the syntax .PP .Vb 1 \& ENV{LD_LIBRARY_PATH} = ${prefix}/lib .Ve .PP will enhance the \s-1LD_LIBRARY_PATH\s0 appropriately. .PP Note that this only works for options set in an options file. It does not work for options set on the command line, from the environment itself, or from the program-supplied default. .PP Under some circumstances, the perl interpreter will need to be restarted in order to pick up the new \s-1LD_LIBRARY_PATH.\s0 In that case, you can include the special option .PP .Vb 1 \& perl_restart = 1 .Ve .PP An example of where this might be useful is for \s-1CGI\s0 scripts that use the \s-1DBI\s0 and DBD::Oracle because the Oracle libraries are dynamically linked at runtime. .PP \&\s-1NOTE:\s0 The other standard way to handle \s-1CGI\s0 scripts which require special environment variables to be set is with Apache directives in the httpd.conf or .htaccess files. i.e. .PP .Vb 2 \& SetEnv LD_LIBRARY_PATH /home/oracle/oracle/product/10.2.0/oraclient/lib \& SetEnv ORACLE_HOME /home/oracle/oracle/product/10.2.0/oraclient .Ve .PP \&\s-1NOTE:\s0 Yet another standard way to handle \s-1CGI\s0 scripts which require an enhanced \s-1LD_LIBRARY_PATH\s0 specifically is to use the /etc/ld.so.conf file. Edit /etc/ld.so.conf and then run ldconfig (as root). This adds your specific path to the \*(L"standard system places\*(R" that are searched for shared libraries. This has nothing to do with App::Options or environment variables of course. .SS "import and flush_imports" .IX Subsection "import and flush_imports" After each option file is read, the special option \*(L"flush_imports\*(R" is checked. If set, the list of pending option files to be parsed is cleared, and the flush_imports option is also cleared. .PP This is useful if you do not want to inherit any of the option values defined in system-wide option files. .PP The special option \*(L"import\*(R" is checked next. If it is set, it is understood to be a list of option files (separated by /[,; ]+/) to be prepended to the list of pending option files. The import option itself is cleared. .SS "Other Environment Variables and Defaults" .IX Subsection "Other Environment Variables and Defaults" After command line options and option files have been parsed, all of the other options which are known to the program are checked for environment variables and defaults. .PP Options can be defined for the program with either the \&\*(L"options\*(R" arg or the \*(L"option\*(R" arg to the \fIinit()\fR method (or a combination of both). .PP .Vb 10 \& use App::Options ( \& options => [ "dbname", "dbuser", "dbpass" ], \& option => { \& dbname => { \& env => "DBNAME", \& default => "devel", \& }, \& dbuser => { \& env => "DBUSER;DBI_USER", \& }, \& dbpass => { \& env => "", # password in %ENV is security breach \& }, \& }, \& ); .Ve .PP For each option variable known, if the value is not already set, then the environment is checked, the default is checked, variable expansion is performed, and the value is entered into the option hash. .SS "Special Option prefix" .IX Subsection "Special Option prefix" The special option \*(L"prefix\*(R" is reconciled and finalized next. .PP Unless it was specified on the command line, the original \*(L"prefix\*(R" was autodetected. This may have resulted in a path which was technically correct but was different than intended due to symbolic linking on the file system. .PP Since the \*(L"prefix\*(R" variable may also be set in an option file, there may be a difference between the auto-detected \*(L"prefix\*(R" and the option file \*(L"prefix\*(R". If this case occurs, the option file \*(L"prefix\*(R" is the one that is accepted as authoritative. .SS "Special Option perlinc" .IX Subsection "Special Option perlinc" One of the primary design goals of App::Options was to be able to support multiple installations of software on a single machine. .PP Thus, you might have different versions of software installed under various directories such as .PP .Vb 3 \& /usr/product1/1.0.0 \& /usr/product1/1.1.0 \& /usr/product1/2.1.5 .Ve .PP Naturally, slightly different versions of your perl modules will be installed under each different \*(L"prefix\*(R" directory. When a program runs from /usr/product1/1.1.0/bin, the \*(L"prefix\*(R" will by \*(L"/usr/product1/1.1.0\*(R" and we want the \f(CW@INC\fR variable to be modified so that the appropriate perl modules are included from \f(CW$prefix\fR/lib/*. .PP This is where the \*(L"perlinc\*(R" option comes in. .PP If \*(L"perlinc\*(R" is set, it is understood to be a list of paths (separated by /[ ,;]+/) to be prepended to the \f(CW@INC\fR variable. .PP If \*(L"perlinc\*(R" is not set, \&\*(L"$prefix/lib/perl5/$perlversion\*(R" and \&\*(L"$prefix/lib/perl5/site_perl/$perlversion\*(R" are automatically prepended to the \f(CW@INC\fR variable as a best guess. .SS "Special Option debug_options" .IX Subsection "Special Option debug_options" If the \*(L"debug_options\*(R" variable is set (often on the command line), the list of option files that was searched is printed out, the resulting list of variable values is printed out, and the resulting list of include directories (@INC) is printed out. .SS "Version" .IX Subsection "Version" After all values have been parsed, various conditions are checked to see if the program should print diagnostic information rather than continue running. Two of these examples are \-\-version and \-\-help. .PP If the \*(L"\-\-version\*(R" option is set on the command line, the version information for all loaded modules is printed, and the program is exited. (The version of a package/module is assumed to be the value of the \f(CW$VERSION\fR variable in that package. i.e. The version of the XYZ::Foo package is \f(CW$XYZ::Foo::VERSION\fR.) .PP .Vb 1 \& prog \-\-version .Ve .PP Of course, this is all done implicitly in the \s-1BEGIN\s0 block (during \&\*(L"use App::Options;\*(R"). If your program tried to set \&\f(CW$main::VERSION\fR, it may not be set unless it is set explicitly in the \s-1BEGIN\s0 block. .PP .Vb 5 \& #!/usr/bin/perl \& BEGIN { \& $VERSION = "1.12"; \& } \& use App::Options; .Ve .PP This can be integrated with \s-1CVS\s0 file versioning using something like the following. .PP .Vb 5 \& #!/usr/bin/perl \& BEGIN { \& $VERSION = do { my @r=(q$Revision: 14478 $=~/\ed+/g); sprintf "%d."."%02d"x$#r,@r}; \& } \& use App::Options; .Ve .PP Furthermore, the version information about some modules that you might expect to have seen will not be printed because those modules have not yet been loaded. To fix this, use the \-\-version_packages option (or set it in an option file). This option contains a comma-separated list of modules and/or module regular expressions. The modules are loaded, and the version information from all resulting packages that match any of the patterns is printed. .PP .Vb 2 \& prog \-\-version \-\-version_packages=CGI \& prog \-\-version \-\-version_packages=CGI,Template .Ve .PP This also cuts down on the miscellaneous modules (and pragmas) which might have cluttered up your view of the version information you were interested in. If you really wish to see version information for all modules, use the \-\-version=all option. .PP .Vb 1 \& prog \-\-version=all \-\-version_packages=CGI,Template .Ve .SS "Help and Validations" .IX Subsection "Help and Validations" If the \*(L"\-?\*(R" or \*(L"\-\-help\*(R" options were set on the command line, the usage statement is printed, and the program is exited. .PP Then each of the options which is defined may be validated. .PP If an option is designated as \*(L"required\*(R", its value must be defined somewhere (although it may be the empty string). (If it is also required to be a non-empty string, a regex may be provided for the type, i.e. type => \*(L"/./\*(R".) .PP If an option is designated as having a \*(L"type\*(R", its value must either be undefined or match a specific regular expression. .PP .Vb 11 \& Type Regular Expression \& ========= ========================================= \& string (any) \& integer /^\-?[0\-9_]+$/ \& float /^\-?[0\-9_]+\e.?[0\-9_]*([eE][+\-]?[0\-9_]+)?$/ \& (or) /^\-?\e.[0\-9_]+([eE][+\-]?[0\-9_]+)?$/ \& boolean /^[01]$/ \& date /^[0\-9]{4}\-[01][0\-9]\-[0\-3][0\-9]$/ \& datetime /^[0\-9]{4}\-[01][0\-9]\-[0\-3][0\-9] [0\-2][0\-9]:[0\-5][0\-9]:[0\-5][0\-9]$/ \& time /^[0\-2][0\-9]:[0\-5][0\-9]:[0\-5][0\-9]$/ \& /regexp/ /regexp/ .Ve .PP Note that an arbitrary regular expression may be designated as the \*(L"type\*(R" by enclosing it in slashes (i.e. \*(L"/^[\s-1YN\s0]$/\*(R"). .PP If the options fail any of the \*(L"required\*(R" or \*(L"type\*(R" validation tests, the \fIApp::Options::print_usage()\fR function is called to print out a usage statement and the program is exited. .SH "USAGE TUTORIAL" .IX Header "USAGE TUTORIAL" .SS "Getting Started" .IX Subsection "Getting Started" Create a perl program called \*(L"demo1\*(R". .PP .Vb 6 \& #!/usr/bin/perl \& use App::Options; \& print "Wow. Here are the options...\en"; \& foreach (sort keys %App::options) { # options appear here! \& printf("%\-20s => %s\en", $_, $App::options{$_}); \& } .Ve .PP Run it different kinds of ways to see how it responds. .PP .Vb 10 \& demo1 \& demo1 \-x \& demo1 \-x \-\-verbose \& demo1 \-\-x \-verbose \& demo1 \-x=5 \-\-verbose=10 \-\-foo=bar \& demo1 \-\-help \& demo1 \-x=8 \-\-help \& demo1 \-? \& demo1 \-\-debug_options \-? \& demo1 \-x=5 \-\-verbose=10 \-\-foo=bar \-\-debug_options \-? \& \& demo1 \-\-version \& demo1 \-\-version \-\-version_packages=CGI .Ve .PP Now create a copy of the program. .PP .Vb 1 \& cp demo1 demo2 .Ve .PP Start putting entries like the following .PP .Vb 6 \& x = 7 \& hello = world \& [demo2] \& verbose=3 \& [/demo/] \& baz = foo .Ve .PP in the following files .PP .Vb 10 \& $HOME/.app/demo1.conf \& $HOME/.app/demo2.conf \& $HOME/.app/app.conf \& demo1.conf (same directory as the demo* programs) \& demo2.conf (same directory as the demo* programs) \& app.conf (same directory as the demo* programs) \& $PREFIX/etc/app/demo1.conf \& $PREFIX/etc/app/demo2.conf \& $PREFIX/etc/app/app.conf \& /etc/app/app.conf .Ve .PP and see how the programs respond in each different case. .PP Next set environment variables like the following and see how the programs respond. .PP .Vb 4 \& export APP_X=14 \& export APP_VERBOSE=7 \& export APP_FOO=xyzzy \& export APP_HELLO=Plugh! .Ve .PP You are well on your way. .SS "A Development Scenario" .IX Subsection "A Development Scenario" Now let's imagine that we are writing a suite of programs which operate on a relational database. These programs are part of a larger system which goes through a development cycle of development, test, and production. Each step in the development cycle, the programs will run against different databases, but we don't want that to affect the code. .PP Let's suppose that we write a program which lists the customers in a customer table. .PP .Vb 9 \& create table person ( \& person_id integer not null auto_increment primary key, \& first_name varchar(99) null, \& last_name varchar(99) null, \& birth_dt date null, \& company_id integer null, \& wholesale_ind char(1) null, \& change_dttm datetime not null, \& ); .Ve .PP We call this program \*(L"listcust\*(R". .PP .Vb 12 \& #!/usr/bin/perl \-e \& use strict; \& use App::Options; \& use DBI; \& my $dsn = "dbi:$App::options{dbdriver}:database=$App::options{dbname}"; \& my $dbh = DBI\->connect($dsn, $App::options{dbuser}, $App::options{dbpass}); \& my $sql = "select first_name, last_name, birth_dt, company_id, wholesale_ind, change_dttm from person"; \& my $cust = $dbh\->selectall_arrayref($sql); \& foreach my $row (@$cust) { \& printf("%\-24 %\-24 %s %9d %s\en", @$row); \& } \& $dbh\->disconnect(); .Ve .PP Then you can invoke this program with all of the command line options and everything works fine. .PP .Vb 1 \& listcust \-\-dbdriver=mysql \-\-dbname=prod \-\-dbuser=scott \-\-dbpass=tiger .Ve .PP However, if you don't use all of the options, you will get a \s-1DBI\s0 error. Furthermore, \*(L"listcust \-\-help\*(R" doesn't help very much. A system administrator confronting this problem would put the following lines into \&\*(L"$PREFIX/etc/app/app.conf\*(R" or \*(L"$PREFIX/etc/app/listcust.conf\*(R". .PP .Vb 4 \& dbdriver = mysql \& dbname = prod \& dbuser = scott \& dbpass = tiger .Ve .PP If, however, your projects were not in the habit of using the \&\s-1PREFIX\s0 environment variable and the program is not installed in \&\f(CW$PREFIX\fR/bin, he would have to put the above lines in either the \*(L"app.conf\*(R" file or the \*(L"listcust.conf\*(R" file in the same directory as \*(L"listcust\*(R" or in the global \&\*(L"/etc/app/app.conf\*(R" option file. .PP A user (without privileges to the \*(L"$PREFIX/etc/app\*(R" directory or the directory in which \*(L"listcust\*(R" lives) would have to put the described lines into \*(L"$HOME/.app/app.conf\*(R" or \&\*(L"$HOME/.app/listcust.conf\*(R". .PP Putting the options in any of those files would make \*(L"\-\-help\*(R" print something intelligent. .PP A developer, however, might decide that the program should have some defaults. .PP .Vb 8 \& use App::Options ( \& option => { \& dbdriver => "mysql", \& dbname => "prod", \& dbuser => "scott", \& dbpass => "tiger", \& }, \& ); .Ve .PP (This supplies defaults and also makes \*(L"\-\-help\*(R" print something intelligent, regardless of whether there are any configuration files.) .PP If all you wanted to do was provide defaults for options, this format would be fine. However, there are other useful attributes of an option besides just the \*(L"default\*(R". To use those, you generally would use the more complete form of the \*(L"option\*(R" arg. .PP .Vb 8 \& use App::Options ( \& option => { \& dbdriver => { default => "mysql", }, \& dbname => { default => "prod", }, \& dbuser => { default => "scott", }, \& dbpass => { default => "tiger", }, \& }, \& ); .Ve .PP Then we can indicate that these options are all required. If they are not provided, the program will not run. .PP Meanwhile, it makes no sense to provide a \*(L"default\*(R" for a password. We can remove the default, but if we ever tried to run the program without providing the password, it would not get past printing a \*(L"usage\*(R" statement. .PP .Vb 8 \& use App::Options ( \& option => { \& dbdriver => { required => 1, default => "mysql", }, \& dbname => { required => 1, default => "prod", }, \& dbuser => { required => 1, default => "scott", }, \& dbpass => { required => 1, }, \& }, \& ); .Ve .PP We now might enhance the code in order to list only the customers which had certain attributes. .PP .Vb 10 \& my $sql = "select first_name, last_name, birth_dt, company_id, wholesale_ind, change_dttm from person"; \& my (@where); \& push(@where, "first_name like \*(Aq%$App::options{first_name}%\*(Aq") \& if ($App::options{first_name}); \& push(@where, "last_name like \*(Aq%$App::options{last_name}%\*(Aq") \& if ($App::options{last_name}); \& push(@where, "birth_dt = \*(Aq$App::options{birth_dt}\*(Aq") \& if ($App::options{birth_dt}); \& push(@where, "company_id = $App::options{company_id}") \& if ($App::options{company_id}); \& push(@where, "wholesale_ind = \*(Aq$App::options{wholesale_ind}\*(Aq") \& if ($App::options{wholesale_ind}); \& push(@where, "change_dttm >= \*(Aq$App::options{change_dttm}\*(Aq") \& if ($App::options{change_dttm}); \& if ($#where > \-1) { \& $sql .= "\enwhere " . join("\en and ", @where) . "\en"; \& } \& my $cust = $dbh\->selectall_arrayref($sql); .Ve .PP The \fIinit()\fR method call might be enhanced to look like this. Also, the order that the options are printed by \*(L"\-\-help\*(R" can be set with the \*(L"options\*(R" argument. (Otherwise, they would print in alphabetical order.) .PP .Vb 10 \& use App::Options ( \& options => [ "dbdriver", "dbname", "dbuser", "dbpass", \& "first_name", "last_name", "birth_dt", "company_id", \& "wholesale_ind", "change_dttm", \& ], \& option => { \& dbdriver => { \& description => "dbi driver name", \& default => "mysql", \& env => "DBDRIVER", # use a different env variable \& required => 1, \& }, \& dbname => { \& description => "database name", \& default => "prod", \& env => "DBNAME", # use a different env variable \& required => 1, \& }, \& dbuser => { \& description => "database user", \& default => "scott", \& env => "DBUSER;DBI_USER", # check both \& required => 1, \& }, \& dbpass => { \& description => "database password", \& env => "", # disable env for password (insecure) \& required => 1, \& secure => 1, # FYI. This is inferred by the fact that "dbpass" \& # ends in "pass", so it is not necessary. \& }, \& first_name => { \& description => "portion of customer\*(Aqs first name", \& }, \& last_name => { \& description => "portion of customer\*(Aqs last name", \& }, \& birth_dt => { \& description => "customer\*(Aqs birth date", \& type => "date", \& }, \& company_id => { \& description => "customer\*(Aqs company ID", \& type => "integer", \& }, \& wholesale_ind => { \& description => "indicator of wholesale customer", \& type => "/^[YN]$/", \& }, \& change_dttm => { \& description => "changed\-since date/time", \& type => "datetime", \& }, \& }, \& ); .Ve .PP It should be noted in the example above that the default environment variable name (\*(L"APP_${varname}\*(R") has been overridden for some of the options. The \*(L"dbname\*(R" variable will be set from \*(L"\s-1DBNAME\*(R"\s0 instead of \*(L"\s-1APP_DBNAME\*(R". \s0 The \*(L"dbuser\*(R" variable will be set from either \*(L"\s-1DBUSER\*(R"\s0 or \*(L"\s-1DBI_USER\*(R".\s0 .PP It should also be noted that if only the order of the options rather than all of their attributes were desired, the following could have been used. .PP .Vb 6 \& use App::Options ( \& options => [ "dbdriver", "dbname", "dbuser", "dbpass", \& "first_name", "last_name", "birth_dt", "company_id", \& "wholesale_ind", "change_dttm", \& ], \& ); .Ve .PP Using the \*(L"options\*(R" arg causes the options to be printed in the order given in the \*(L"\-\-help\*(R" output. Then the remaining options defined in the \*(L"option\*(R" arg are printed in alphabetical order. All other options which are set on the command line or in option files are printed if the \&\*(L"show_all\*(R" option is set. This option is off by default if either the \*(L"options\*(R" arg or the \*(L"option\*(R" arg are supplied and on if neither are supplied. .PP If, for some reason, the program needed to put the options into a different option hash (instead of \f(CW%App::options\fR) or directly specify the option file to use (disregarding the standard option file search path), it may do so using the following syntax. .PP .Vb 4 \& use App::Options ( \& values => \e%Mymodule::opts, \& option_file => "/path/to/options.conf", \& ); .Ve .PP If, for some reason, the program needs to inhibit one or more of the sources for options, it can do so with one of the following arguments. Of course, inhibiting all three would be a bit silly. .PP .Vb 5 \& use App::Options ( \& no_cmd_args => 1, \& no_option_file => 1, \& no_env_vars => 1, \& ); .Ve .SS "A Deployment Scenario" .IX Subsection "A Deployment Scenario" Sometimes a software system gets deployed across many machines. You may wish to have a single option file set different values when it is deployed to different machines. .PP For this purpose, the automatic \*(L"host\*(R" and \*(L"hostname\*(R" values are useful. Suppose you have four servers named \*(L"foo1\*(R", \*(L"foo2\*(R", \&\*(L"foo3\*(R", and \*(L"foo4\*(R". You may wish the software to use different databases on each server. So app.conf might look like this. .PP .Vb 7 \& [host=foo1] dbname = devel \& [host=foo2] \& dbname = test \& [host=foo3] \& dbname = prod \& [ALL] \& dbname = prod .Ve .PP Hopefully, that's enough to get you going. .PP I welcome all feedback, bug reports, and feature requests. .SH "ACKNOWLEDGEMENTS" .IX Header "ACKNOWLEDGEMENTS" .Vb 3 \& * (c) 2010 Stephen Adkins \& * Author: Stephen Adkins \& * License: This is free software. It is licensed under the same terms as Perl itself. .Ve .SH "SEE ALSO" .IX Header "SEE ALSO"