Perl Programming Page 4 - Command Line Options in Perl: Using Getopt::Std |
The Getopt::Std module provides one extra bit of functionality that's worth mentioning. Often, you'll want to provide switches that will make the program display help information or print version information. You can define and check for these switches yourself, printing out the relevant information if necessary. This isn't very difficult. However, it's also possible to let Getopt::Std do the checking for you. For help information, Getopt::Std will check for “--help.” Note that this is a long option. If this switch is present, then the module will print out basic help information, such as version information and a list of options. The only thing you should do is set $Getopt::Std::STANDARD_HELP_VERSION to a true value:
$Getopt::Std::STANDARD_HELP_VERSION = 1;
If we use the help switch on our last example, the output will look something like this:
./getopt_6 version [unknown] calling Getopt::Std::getopts (version 1.05), running under Perl version 5.10.0.
Usage: getopt_6 [-OPTIONS [-MORE_OPTIONS]] [--] [PROGRAM_ARG1 ...]
The following single-character options are accepted: With arguments: -a -b Boolean (without arguments): -c
Options may be merged together. -- stops processing of options. Space is not required between options and their arguments.
For version information, Getopt::Std will check for “--version.” The output will, by default, look something like this:
./getopt_6 version [unknown] calling Getopt::Std::getopts (version 1.05), running under Perl version 5.10.0.
Notice how this same information is printed first in the help output. It's possible to change these messages, though, by simply defining two functions, HELP_MESSAGE and VERSION_MESSAGE. Both functions are passed a file handle, and all that's necessary is for you to write the proper message to that file handle. Let's define both methods to provide some more appropriate messages:
sub HELP_MESSAGE { my $fh = shift; print $fh "t-attTakes a valuen"; print $fh "t-bttTakes a value as welln"; print $fh "t-cttDoes not take a valuen"; print $fh "nt--helpttDisplays thisn"; print $fh "t--versiontDisplays version informationn";}sub VERSION_MESSAGE { my $fh = shift; print $fh "My Application version 1.0n";}
Now, when the help or version switches are used, the program will print out the new, custom messages automatically. That saves you, the developer, a bit of time and effort in checking for the switches yourself.
blog comments powered by Disqus |
|
|
|
|
|
|
|