cpan intermediate

How to parse command line options with Getopt::Long in Perl?

Question

How to parse command line options with Getopt::Long in Perl?

Parsing command line options in Perl is commonly done using the Getopt::Long module, which provides a flexible way to handle named options, flags, and even complex option specifications. Unlike the basic ARGV array processing, Getopt::Long makes it easy to define options with different types (strings, integers, booleans) and supports TMTOWTDI ("There’s more than one way to do it") by allowing multiple ways to specify options.

Basics of Getopt::Long

Using Getopt::Long involves:

  • Declaring variables to hold option values.
  • Calling GetOptions with specifications that map command line flags to variables.

Option specifications include the option name, followed by optional type indicators like =s for strings, =i for integers, and ! for booleans (enable/disable).

Important Perl Concepts in This Context

  • Sigils: The option variables often use scalar sigil $ for single values and arrays @ for options that can appear multiple times.
  • Context: Getopt::Long modifies the variables you pass it in place.
  • TMTOWTDI: The module supports flexible specification formats, e.g. --flag=val or --flag val.

Example: Parsing Options with Getopt::Long

use strict;
use warnings;
use Getopt::Long;

# Variables to hold option values
my $name = 'World';      # string option with default
my $repeat = 1;          # integer option with default
my $help = 0;            # boolean flag
my @tags = ();           # multiple value option

# Parse command line options
GetOptions(
    "name=s"   => \$name,     # string option (--name foo)
    "repeat=i" => \$repeat,   # integer option (--repeat 3)
    "help|h"   => \$help,     # boolean flag (--help or -h)
    "tag=s@"   => \@tags,     # multiple string option (--tag val) repeatable
) or die "Error parsing options\n";

# If help flag set, print usage and exit
if ($help) {
    print "Usage: perl script.pl [--name NAME] [--repeat NUM] [--tag TAG]... [--help]\n";
    exit;
}

# Print output showing parsed options
print "Hello, $name!\n";
print "Repeating $repeat times:\n";

for my $i (1..$repeat) {
    print "  Iteration $i\n";
}

if (@tags) {
    print "Tags specified: " . join(", ", @tags) . "\n";
} else {
    print "No tags specified.\n";
}

Explanation

  • name=s means the --name option expects a string.
  • repeat=i means --repeat expects an integer.
  • help|h means the flag can be --help or -h, boolean toggle.
  • tag=s@ means a string option that can be repeated multiple times, values are collected into an array.
  • Options are passed by reference, so changes happen directly to the variables.

Common Pitfalls

  • Forgetting to use backslash references: GetOptions requires references (e.g., \$name), or it won’t modify your variables.
  • Misunderstanding types: Using =s for integers or vice versa can cause parsing errors or unexpected values.
  • Mixing options and positional arguments: Getopt::Long removes recognized options from @ARGV by default, so you get leftover positional arguments after.
  • Boolean flags: Use =! if you want explicit enable/disable (e.g. --flag! / --noflag), otherwise absence/presence toggles boolean variables.

Version Notes

Getopt::Long is a core module available in all Perl releases from 5.6+. From Perl 5.10 onward, it supports enhanced option specification syntax and features like whitespace-insensitive parsing.

Using GetOptions simplifies robust command line parsing and is a recommended practice over manual @ARGV handling for medium or complex CLI scripts.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 42ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Hello, World!
Repeating 1 times:
  Iteration 1
No tags specified.
STDERR
(empty)

Was this helpful?

Related Questions