Perl Programming Page 3 - Using Getopt::Long: More Command Line Options in Perl |
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:
#!/usr/bin/perluse strict;use Getopt::Long;my $verbose = 0;GetOptions('verbose:i' => $verbose);print "verbose: $verbosen";
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:
$ program --name Bob --name Anne
Here's how this would look like in Perl:
my @names;GetOptions('names=s' => @names);print "$_n" for (@names);
The @names array would contain an element for each value. If we called the program as we did above, it would contain “Bob” and “Anne.”
blog comments powered by Disqus |
|
|
|
|
|
|
|