Options with Getopt::Long
Parsing options
@ARGV holds everything the shell passed after the script name, but splitting it by hand gets old after the second flag. Getopt::Long ships with Perl and does the job properly.
#!/usr/bin/perl use strict; use warnings; use Getopt::Long; my %opt = (verbose => 0, output => "-"); GetOptions( \%opt, "verbose|v+", "output|o=s", ) or die "usage: backup.pl [--verbose] [--output FILE]\n"; print "verbose: $opt{verbose}\n"; print "output: $opt{output}\n";
Each string describes one option: the name, optional aliases after a pipe, and a type suffix. The results land in the hash you passed by reference, so --verbose sets $opt{verbose}.
./backup.pl --verbose --output=log.txt
verbose: 1
output: log.txt
GetOptions returns false on a bad option and prints a warning of its own. Check the return value, otherwise a typo like --verbse silently does nothing.
Option types
The suffix after the option name decides what the user may write and what you receive. Four characters cover almost every command line tool:
GetOptions( \%opt, "verbose|v+", # counter: -v -v "force!", # boolean, --force / --noforce "output|o=s", # required string "tag=s@", # repeatable string "workers|j=i", # integer );
A bare name is a flag. The plus sign makes a counter, so -vvv gives three when bundling is enabled. The exclamation mark adds a negated form, and the at sign collects repeated values into an array reference.
Options accept both --output log.txt and --output=log.txt. Single letters also work with one dash: -o log.txt. To allow -vv as a bundle of single letters, configure it explicitly:
Getopt::Long::Configure("bundling");
Call Configure before GetOptions, once per program. Other useful settings are no_ignore_case to keep -v and -V distinct, and auto_abbrev to accept unique prefixes like --verb.
Positional arguments
Whatever is not an option stays in @ARGV, which is how you take file names after the flags. By default parsing stops at the first non-option word, so the rest is yours untouched:
use strict; use warnings; use Getopt::Long; my %opt = (verbose => 0); GetOptions(\%opt, "verbose|v+") or die "usage: backup.pl [-v] DIR...\n"; my @files = @ARGV; die "no input files\n" unless @files; for my $file (@files) { print "processing $file\n"; }
./backup.pl -v src/ lib/
processing src/
processing lib/
If you want flags to be recognised after file names too — backup.pl src/ --verbose — enable permutation. Use GetOptionsFromArray(\@args, \%opt, ...) when the words do not come from @ARGV, for example in a wrapper script that forwards arguments.
--help with Pod::Usage
A tool without --help is a tool nobody else can use. The clean way is to write the help text as POD at the bottom of the script and let Pod::Usage print it:
use strict; use warnings; use Getopt::Long; use Pod::Usage; my %opt = (verbose => 0, output => "-"); GetOptions( \%opt, "help|h" => sub { pod2usage(-exitval => 0, -verbose => 1) }, "verbose|v+", "output|o=s", ) or pod2usage(-exitval => 2); __END__ =head1 NAME backup.pl - copy a folder into an archive =head1 SYNOPSIS backup.pl [--verbose] [--output FILE] DIR...
-verbose => 2 prints the full manual page instead of the synopsis. Setting -exitval => 2 on a parse failure is the convention that tells a calling script the arguments were wrong, as opposed to the work failing later.
./backup.pl --help
Usage:
backup.pl [--verbose] [--output FILE] DIR...
Write the synopsis once and let it serve both the help screen and the manual page. Users read it, and so will you in six months.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Getopt::Longdo for a program?Answer
It parses @ARGV into a hash of options and ships with Perl
The module is in the core, and GetOptions fills the hash you pass it with the values of the options it found.
-
What does the plus sign in
"verbose|v+"mean?Answer
The option is a counter that increases each time it is used
Each use adds one, so -vv gives 2 once bundling is enabled and two separate -v flags work without it.
-
What does the
=ssuffix in"output|o=s"mean?Answer
The option needs a string value
The equals sign says a value follows, and the letter names the type: s for string, i for integer, f for number.
-
What does the exclamation mark in
"force!"add?Answer
A --noforce form that sets the value to false
The negated form is how a user turns a flag off again, and both forms set the same hash entry.
-
After
GetOptionsreturns, what is left in@ARGV?Answer
The words that were not options
The leftover words are the positional arguments, which is how a tool takes file names after its flags.
-
What does
Getopt::Long::Configure("bundling")allow?Answer
Single-letter options written together, so -vv means two of them
Without bundling each dash takes one option, and the setting must be made before the GetOptions call.
-
What does this program print?
use Getopt::Long; my %opt = (verbose => 0); @ARGV = ("-v", "-v", "src/"); GetOptions(\%opt, "verbose|v+") or die "bad options\n"; print "$opt{verbose}\n";Answer
2
The counter is increased by each flag, and the word src/ is not an option so it stays in @ARGV.
-
What does this program print?
use Getopt::Long; my %opt = (force => 1); @ARGV = ("--noforce"); GetOptions(\%opt, "force!") or die "bad options\n"; print $opt{force} ? "on\n" : "off\n";Answer
off
The negated form sets the entry to false, so the program prints off.
-
What does this program print?
use Getopt::Long; my %opt; @ARGV = ("--output=log.txt"); GetOptions(\%opt, "output|o=s") or die "bad options\n"; print $opt{output}, "\n";Answer
log.txt
The equals form passes the value to the string option, which stores it under output.
-
What does this program print?
use Getopt::Long; my %opt; @ARGV = ("--tag=a", "--tag=b"); GetOptions(\%opt, "tag=s@") or die "bad options\n"; print join(",", @{ $opt{tag} }), "\n";Answer
a,b
The at sign collects repeated values into an array reference, and join writes them with a comma.
Article author: Arthur Isaev