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/perl
use strict;
use warnings;
use Getopt::Long;

# This is only neccesary when using strict. Which is always.
my ($flag, $compulsory_string, $optional_string, $compulsory_integer, $optional_integer, $compulsory_

GetOptions(
        "o"=>\$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 $flag;
print $compulsory_float."\n" if $compulsory_float;
print $compulsory_integer."\n" if $compulsory_integer;
print $compulsory_string."\n" if $compulsory_string;
print $optional_float."\n" if $optional_float;
print $optional_integer."\n" if $optional_integer;
print $optional_string."\n" if $optional_string;

Posted

in

by

Tags: