Perl Programming Using Getopt::Long: More Command Line Options in Perl |
The Getopt::Std module allows you to read and respond to short options, that can either take values or function as boolean values. The module even aids in the creation of help and version information, taking much of the work out of things. However, sometimes you'll need to support a large number of command line options, and representing each of them with a single letter becomes quite impractical after a certain point. Besides, short options can easily become very cryptic for the end user of your application. Fortunately, Perl makes it very easy to work with long options too, which, as you remember, can be represented by multiple letters. By making use of the appropriately-named Getopt::Long module, you can easily add broader support for command line options into your application. In this article, we'll take a look at the Getopt::Long module and the functionality it offers for processing command line options. Getting started With Getopt::Std, we only had to call one function to process all of the command line options. That one function would then populate global variables (by default) with option values. Getopt::Long also has a single function, GetOptions, which handles the command line options, but it's more complex. This function takes an even number of arguments, where the odd-numbered arguments are the option names (actually, they are the “specifications” and can contain more than just the names, but we'll get into that later), and the even-numbered arguments are references to variables where the option values will be stored (again, it gets more complex than this—these are actually the “destinations”). Let's see what this looks like in an actual script. Consider a program that can take just one command line option. This command line option will be named “force” and will make the program force some sort of operation. It doesn't matter what that operation is because we're not concerned with that here. We're only concerned with the command line options, so let's just print out the value of the command line option. Obviously, the option will have a boolean value, since it doesn't take any values. If it's present, it's true. Otherwise, it's false. We could call the program like this:
$ program --force
Or like this:
$ program
Here's what the full script looks like:
#!/usr/bin/perluse strict;use Getopt::Long;my $force = '';GetOptions('force' => $force);print "force: $forcen";
As you can see, there's nothing complicated here. The only thing you should keep in mind is that the variables you use need default values. Otherwise, if the command line option isn't present, and you use the variable later on, you'll get a warning if you have warnings enabled.
blog comments powered by Disqus |
|
|
|
|
|
|
|