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;
  5.  
  6. # This is only neccesary when using strict. Which is always.
  7. my ($flag, $compulsory_string, $optional_string, $compulsory_integer, $optional_integer, $compulsory_
  8.  
  9. GetOptions(
  10. "o"=>\$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. );
  18.  
  19. print "flag set\n" if $flag;
  20. print $compulsory_float."\n" if $compulsory_float;
  21. print $compulsory_integer."\n" if $compulsory_integer;
  22. print $compulsory_string."\n" if $compulsory_string;
  23. print $optional_float."\n" if $optional_float;
  24. print $optional_integer."\n" if $optional_integer;
  25. print $optional_string."\n" if $optional_string;