# 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:

#!/usr/bin/perluse strict;use warnings;use Getopt::Long; # This is only neccesary when using strict. Which is always.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_ GetOptions(        "o"=>\<span class="katex math inline">flag,        "cfloat=f"=>\$compulsory_float, "cint=i"=>\$compulsory_integer,        "cstring=s"=>\$compulsory_string, "ofloat:f"=>\$optional_float,        "oint:i"=>\$optional_integer, "ostring:s"=>\$optional_string,); print "flag set\n" if</span>flag;print <span class="katex math inline">compulsory_float."\n" if</span>compulsory_float;print <span class="katex math inline">compulsory_integer."\n" if</span>compulsory_integer;print <span class="katex math inline">compulsory_string."\n" if</span>compulsory_string;print <span class="katex math inline">optional_float."\n" if</span>optional_float;print <span class="katex math inline">optional_integer."\n" if</span>optional_integer;print <span class="katex math inline">optional_string."\n" if</span>optional_string;