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 GetOptions function, as we've used it now, sets variables according to the values of command line options, or whether or not command line options are present. We can respond to these command line options by examining the variables later on the program. Sometimes, this is the appropriate approach.
Other times, however, this is really inconvenient. Suppose we need more control over what happens when a command line option is encountered. Perhaps we want to set a variable whose value is determined by modifying the value from the command line.
In order to do this, we can use a subroutine reference as a command line option's destination in the GetOptions function. This subroutine will be called, with the first argument passed being the option name, and the second option being the value of that option (normally, but we won't get into the exception in this article).
Say that we want to condense multiple spaces in an option's value. We could examine the variable set by GetOptions later on, but why not just collapse everything into one step? We can create a subroutine that does this for us, and then we can reference the subroutine in GetOptions.
It's also possible to pass an anonymous subroutine. This works best for situations where we're not doing a lot of work. Here's our last script's GetOptions function call, rewritten to use an anonymous subroutine:
We'll end our exploration of the Getopt::Long module here. Although there are a number of additional features, I'll leave them to you to uncover. You should at least have the basics down now, which are enough to create functional programs that take advantage of command line options.