Processing Command Line Options with PERL - Hashing It Up (Page 9 of 9 )
If you'd prefer, you can also store all command-line options directly in a hash, instead of creating separate scalars for each. The procedure is fairly simple; all you need to do is pass a reference to the hash variable as the first argument to GetOptions(), followed by the names of the options to be stored in it. Consider the following example:
#!/usr/bin/perl
# import module
use Getopt::Long;
# read options into hash
$result = GetOptions (%options, "base=i", "height=i");
# print hash values
print "Base = " . $options{'base'} . "n";
print "Height = " . $options{'height'} . "n";
print "Area = " . 0.5 * $options{'base'} * $options{'height'} . "n";
Here's the output:
$ ./triangle.pl --base=10 --height=20
Base = 10
Height = 20
Area = 100
In this case, the values passed to the program on the command line are stored in a Perl hash called %options, from whence they can be retrieved using standard hash notation.
Over And Out
And that's about all we have time for. Over the course of the last few pages, I introduced you to one of the more interesting modules in the Perl pantheon, the Getopt::Long.pm module. This module provides a simple API to parse options passed to your Perl scripts at the command line and convert them into Perl scalars or arrays.
With some simple examples, I showed you how to use this API to detect Boolean options, as well as options taking string or numeric values. I also showed you how to create option aliases, and explicitly allow disabling of options with the negation symbol. Finally, I wrapped things up with a demonstration of how you could convert all the options passed on the command-line into a Perl hash, and also showed you how to customize the module to work as per your specific requirements.
If you'd like to read more about this module, consider visiting the following links:
CPAN, at http://www.cpan.org/
Getopt::Long pages on CPAN, at
http://search.cpan.org /search?module=Getopt::Long
Till next time...stay healthy!
Note: Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |