Perl Programming Page 2 - Command Line Options in Perl: Using Getopt::Std |
Let's start by taking a look at the Getopt::Std module. This module provides two functions for parsing short options and isn't very difficult to get started with. With each method, you simply need to specify the letters for short options, and then the module stores the values of those options in the appropriate variables. For example, consider a Perl script named optapp. This application can take two short command line options, a and b. Both of these options take values. We might call this script like this:
$ ./optapp -a20 -b30
In order to actually create this script, we'd use the getopt function of the Getopt::Std module. This function takes one argument, a string containing the letters of all command line options to be recognized. Also, with the getopt function, these command line options must take values. This function is called near the top of the script, and after being called, it will set global variables named $opt_x, where x is the letter of the option. The values of the variables will be the values associated with the options. In the case of the above call, $opt_a would be set to 20, and $opt_b would be set to 30. The resulting script would look like this:
#!/usr/bin/perluse Getopt::Std;getopt('ab');print "$opt_an" if (defined $opt_a);print "$opt_bn" if (defined $opt_b);
As you can see, the script simply prints out the values of the options, if they are used at all. Run the program, passing in some values with the options, and see what you get. Notice, though, that the script doesn't use the strict pragma. If we do use it, then Perl will complain, since $opt_a and $opt_b were never declared. This is a problem, but it's a problem that's easily fixed. We simply need to put in an "our" declaration for each of the names we plan to use. Note that we can't just use "my." We must use "our." Now we can use the strict pragma:
#!/usr/bin/perluse strict;use warnings;use Getopt::Std;our($opt_a, $opt_b);getopt('ab');print "$opt_an" if (defined $opt_a);print "$opt_bn" if (defined $opt_b);
Still, using global variables to store option values is a bit ugly, and every time you need to define a new command line option, it's necessary to declare the associated name using our. Fortunately, we're able to use a hash instead, which makes things easier and keeps our commands neat. To store option values in a hash, just pass a hash reference to the getopt function as the second argument. The keys of the hash correspond to the option names. Here's part of our script rewritten to use a hash rather than global variables:
my %opt;getopt('ab', %opt);print $opt{'a'} . "n" if (defined $opt{'a'});print $opt{'b'} . "n" if (defined %opt{'b'});
The same thing can be accomplished with either method. Just use whatever method you feel looks better.
blog comments powered by Disqus |
|
|
|
|
|
|
|