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.
We just looked at how you can make a command line option take a value. However, there are a few more things you can do with values that are worth mentioning.
First, you can make a value optional for a given command line option. For example, consider a program that normally operates silently, producing no command line output. However, you can give the user the option of making the program produce some output. Many programs operate like this. You can make a command line option called “verbose” that, when present, makes the program produce some output:
$ program --verbose
You might want to give the user the option to make the program print out even more output, though. This can be done by making the command line argument take an integer value that tells the program how verbose to be. A neat solution, though, would be to make this value optional. If the user specifies a value, then that value is used. Otherwise, it defaults to zero. Here's a script that handles such an option:
Second, you'll sometimes want a command line option to be used multiple times with multiple values. The Getopt::Long module allows for this. You simply need to pass an array reference rather than a scalar reference for the destination.
Consider a command line option called “name” that takes a name. We might want to pass multiple names into the program by using this command line option more than once. So, we might run the program like this: