Unlike command line arguments, command line options can sometimes be a bit difficult to read; nevertheless, they can prove to be quite useful. This article explains what a command line option is, why you would use one, and how to process them in Perl. This article is the first of two parts.
The getopt function works fine if you're only dealing with options that take values. However, you'll often need to parse options that do not take values, or some mix of the two. The getopt function does not work for this. Fear not, though, because the getopts function does the trick.
The getopts function operates similarly to the getopt function. It takes a minimum of one argument, which is a string of single-letter options that the program recognizes. However, in this string, you can specify which options take values and which options don't. If a letter appears by itself in the string, then it doesn't take a value, but if there is a colon after the letter, then it does take a value.
The getopts function, like the getopt function, can also take a hash reference in which to store the option values. Otherwise, it will use variables.
To see this in action, let's recreate the script from the last section. However, this time, let's add a third option, c, which does not take a value. Here's the new script (minus the beginning bit):
my%opt;getopts('a:b:c',%opt);print$opt{'a'}."n"if(defined$opt{'a'});print$opt{'b'}."n"if(defined$opt{'b'});print"c option in usen"if($opt{'c'});
As you can see, the program will take two options, a and b, each of which takes a value since a colon follows the letters. Note how we choose to store the values in a hash. The values of this hash corresponding to options a and b will be, of course, the option values. This is the same as before. For c, however, the value will either be 0 or 1. If the option is used, the value is 1. Otherwise, the value is 0.