Getopt in Perl

Oddly, it's taken me until this afternoon to have real need for using getopts in Perl. After a not-overly-brief look around, I've settled on Getopt::Long for the purpose. It's marginally more complicated than the alternative (Getopt::Std), but more flexible and better at error checking.

To use it, you pass a hash of valid options to GetOptions, where the keys are options and the values are the references to variables in which to put their arguments.
The name of the option dictates what value(s) it can hold: the final character indicates type (i - integer, f - float, s - string), and the penultimate whether it is optional or not (= - required, : - optional). Flags are indicated by not following this pattern - they're just given a name with no symbols.

Getopt::Long allows for the shortest unambiguous switch to be used, doesn't distinguish between -o and --o, and allows for the negation of flags (if -flag sets a flag to 1, -noflag will set it to 0). It also doesn't touch @ARGV when it's done getting its flags out of it.

Here's a brief script hopefully helping explain the above:

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Getopt::Long;
  6. # This is only neccesary when using strict. Which is always.
  7. my (<span class="katex math inline">flag,</span>compulsory_string, <span class="katex math inline">optional_string,</span>compulsory_integer, <span class="katex math inline">optional_integer,</span>compulsory_
  9. GetOptions(
  10. "o"=>\<span class="katex math inline">flag,
  11. "cfloat=f"=>\$compulsory_float,
  12. "cint=i"=>\$compulsory_integer,
  13. "cstring=s"=>\$compulsory_string,
  14. "ofloat:f"=>\$optional_float,
  15. "oint:i"=>\$optional_integer,
  16. "ostring:s"=>\$optional_string,
  17. );
  19. print "flag set\n" if</span>flag;
  20. print <span class="katex math inline">compulsory_float."\n" if</span>compulsory_float;
  21. print <span class="katex math inline">compulsory_integer."\n" if</span>compulsory_integer;
  22. print <span class="katex math inline">compulsory_string."\n" if</span>compulsory_string;
  23. print <span class="katex math inline">optional_float."\n" if</span>optional_float;
  24. print <span class="katex math inline">optional_integer."\n" if</span>optional_integer;
  25. print <span class="katex math inline">optional_string."\n" if</span>optional_string;