Using Getopt::Long: More Command Line Options in Perl
In the last article, we took a look at command line options and how we could read them in Perl using the Getopt::Std module. For many simple applications, that article covers all that you need to make use of command line options. When you need more command line options, you can make use of the Getopt::Long module, which is the subject of this article.
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.
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.
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.