Perl Programming Page 2 - Using Getopt::Long: More Command Line Options in Perl |
What if we need for a command line option to take a value, though? This behavior is, of course, supported by the module, but we need to specify that a command line option can take a value. We also need to specify what kind of value the option can take. Suppose we want to add a command line option to our program called “server.” This option will take a value, the address of some server. This value will, of course, be a string. In order to specify all of this, we simply need to add a little bit to the option's specifications (now you know why they are specifications, not names). All we need to add is an equals sign followed by the letter s, which indicates that we're looking for a string:
GetOptions('force' => $force, 'server=s' => $server);
Before this, though, we need to declare the variable and give it a default value:
my $server = '';
You should also adjust the program so that it prints out the value of the option. Now the program can be called with the new command line option:
$ program --server=devshed.com
What happens if we need spaces in the string, though? In that case, we would simply surround the string with quotation marks. For example, consider a command line option named “name” that takes the name of a person:
$ program --name=”John Smith”
We can specify other types of values, too: integers, floating point numbers and “extended integers.” This last type simply corresponds to integers as might be used in Perl. That is, they can be specified in hexadecimal, binary, or whatever. In order to specify that an option takes an integer value, use i, and in order to specify that an option takes a floating point value, use f. Extended integers may be specified by using the letter o. Here are three more command line options. The first takes an integer, the second takes a floating point number, and the third takes an extended integer:
my $retries = 0;my $somefloat = 0;my $einteger = 0;...GetOptions('force' => $force, 'server=s' => $server, 'retries=i' => $retries, 'somefloat=f' => Now we can call the program like this:
$ program --retries=3 –somefloat=3.14 --einteger=0xFF
Say we try to pass the wrong kind of value to an option, though, like this:
$ program --retires=enough
We're passing a string where the program expects a float. If you run this, though, you'll notice that Getopt::Long complains:
Value "hi" invalid for option somefloat (real number expected)
In this case, the value is not assigned to the variable.
blog comments powered by Disqus |
|
|
|
|
|
|
|