Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)
Skepticism and critical thinking is not panacea, but can help to understand the world better

Perl options processing

Old News

Perl options processing

Recommended Books Recommended Links



Perl Language

Generating Help screen     Perl Tips History Humor Etc

Under modern command shells, including those on Unix and Windows, options can be either letters or words. Programs that accept single letters might be invoked like program -a -b -c. Or, they might look be invoked as program -abc, meaning the same thing. If the options take values, you can bundle them together: -aw80L24x is equivalent to -a -w 80 -L 24 -x. With option words, you sacrifice brevity for clarity: program --all --width=80 --length 24 --extend.

In either case, options precede other program arguments (the /tmp in ls -l /tmp) and the parsing stops as soon as a non-option argument is encountered. A double dash by itself immediately terminates option parsing.

These conventions aren't universal but they are sign of good style and it is preferable to adhere to them.

Parsing options in Perl isn't very hard, but reinventing the bycile does not make much sense unless Perl provided solution suiffers from acute overcomplexiry.

There is. In fact, there are several ways to process options ion Perl without writing your own code:

-s Switch

Perl has a built-in support the single-character style options if invoked with the -s switch. For example:

perl -s -f -b myfile.dat

Perl will remove anything that looks like an option (-f and -b) from the command line and set the variables ($f and $b) to true. Here the options should be preceded with a single dash. When Perl encounters an argument without the dash, it finishes options proccessing.


Getopt::Std provides two subroutines, getopt() and getopts(). Each expects a single dash before option letters and stops processing options when the first non-option is detected.

getopt() takes one argument, a string containing all the option letters that expect values. For example, getopt ('lw') lets your program be invoked as program -l24 -w 80 (or program -l 24 -w80), and it will set $opt_l to 24 and $opt_w to 80. Other option letters are also accepted; for example, program -l24 -ab will also set both $opt_a and $opt_b to 1.

When you don't want global variables defined in this way, you can pass a hash reference to getopt(). The keys are the option letters, and the values will be filled with the values (or 1 if the option doesn't take a value).

getopts() allows a little bit more control. Its argument is a string containing the option letters of all recognized options. Options that take values are followed by colons. For example, getopts ('abl:w:') makes your program accept -a and -b without a value, and -l and -w with a value. Any other arguments beginning with a dash result in an error. As with getopt(), a hash reference can be passed as an optional second argument.


Getopt::Long provides the GetOptions() function, which gives you ultimate control over command line options. It provides support for:

Other features:

Option Words. In its standard configuration, GetOptions() handles option words, ignoring case. Options may be abbreviated, as long as the abbreviations are unambiguous. Options and other command line arguments can be mixed; options will be processed first, and the other arguments will remain in @ARGV.

This call to GetOptions() allows a single option, -foo.

GetOptions ('foo' => \$doit);

When the user provides -foo on the command line, $doit is set to 1. In this call, -foo is called the option control string, and \$doit is called the option destination. Multiple pairs of control strings and destinations can be provided. GetOptions() will return true if processing was successful, and false otherwise, displaying an error message with warn().

The option word may have aliases, alternative option words that refer to the same option:

GetOptions ('foo|bar|quux' => \$doit);

If you want to specify that an option takes a string, append =s to the option control string:

GetOptions ('foo=s' => \$thevalue);

When you use a colon instead of an equal sign, the option takes a value only when one is present:

GetOptions ('foo:s' => \$thevalue, 'bar' => \$doit);

Calling this program with arguments -foo bar blech places the string 'bar' in $thevalue, but when called with -foo -bar blech, something different happens: $thevalue is set to an empty string, and $bar is set to 1.

These options can also take numeric values; you can use =i or :i for integer values, and =f or :f for floating point values.

Using and Bundling Single-Letter Options. Using single-letter options is trivial; bundling them is a little trickier. Getopt::Long has a Configure() subroutine that you can use to fine-tune your option parsing. For bundling single-letter options, you would use Getopt::Long::Configure ('bundling'). Now GetOptions() will happily accept bundled single-letter options:

Getopt::Long::Configure ('bundling');
GetOptions ('a' => \$all,
            'l=i' => \$length,
            'w=i' => \$width);

This allows options of the form -a -l 24 -w 80 as well as bundled forms: -al24w80. You can mix these with option words:

GetOptions ('a|all' => \$all,
            'l|length=i' => \$length,
            'w|width=i' => \$width);		

However, the option words require a double dash: --width 24 is acceptable, but -width 24 is not. (That causes the leading w to be interpreted as -w, and results in an error because idth isn't a valid integer value.

Getopt::Long::Configure('bundling_override') allows option words with a single dash, where the words take precedence over bundled single-letter options. For example:

Getopt::Long::Configure ('bundling_override');
GetOptions ('a' => \$a, 'v' => \$v,
            'x' => \$x, 'vax' => \$vax);

This treats -axv as -a -x -v, but treats -vax as a single option word. 

Advanced destinations. You don't need to specify the option destination. If you don't, GetOptions() defines variables $opt_xxx (where xxx is the name of the option), just like getopt() and getopts(). Similarly, GetOptions() also accepts a reference to a hash (as its first argument) and places the option values in it.

If you do specify the option destination, it needn't be a scalar. If you specify an array reference, option values are pushed into this array:

GetOptions ('foo=i' => \@values);

Calling this program with arguments -foo 1 -foo 2 -foo 3 sets @values to (1,2,3).

The option destination can also be a hash reference:

my %values;
GetOptions ('define=s' => \%values);

If you call this program as program -define EOF=-1 -define bool=int, the %values hash will have the keys EOF and bool, set to -1 and 'int' respectively.

Finally, the destination can be a reference to a subroutine. This subroutine will be called when the option is handled. It expects two arguments: the name of the option and the value.

The special option control string '<>' can be used in this case to have a subroutine process arguments that aren't options. This subroutine is then called with the name of the non-option argument. Consider:

GetOptions ('x=i' => \$x, '<>' => \&doit);

When you execute this program with -x 1 foo -x 2 bar this invokes doit() with argument 'foo' (and $x equal to 1, and then calls doit() with argument 'bar' (and $x equal to 2).

Other Configurations. GetOptions() supports several other configuration characteristics. For a complete list, see the Getopt::Long documentation.

Getopt::Long::Configure ('no_ignore_case') matches option words without regard to case.

Getopt::Long::Configure ('no_auto_abbrev') prevents abbreviations for option words.

Getopt::Long::Configure ('require_order') stops detecting options after the first non-option command line argument.

Generating Help screen

 People often ask me why GetOptions() doesn't provide facilities for help message. There are two reasons. The first reason is that while command line options adhere to conventions, help messages don't. Any style of message would necessarily please some people and annoy others, and would make calls to GetOptions() much lengthier and more confusing.

The second reason is that Perl allows a program to contain its own documentation in POD (Plain Old Documentation) format, and there are already modules that extract this information to supply help messages. The following sub-routine uses Pod::Usage for this purpose (and demonstrates how Pod::Usage can be loaded on demand):

sub options () {
    my $help = 0;       # handled locally
    my $ident = 0;      # handled locally
    my $man = 0;        # handled locally
    # Process options.
    if ( @ARGV > 0 ) {
        GetOptions('verbose'=> \$verbose,
                           'trace' => \$trace,
                           'help|?' => \$help,
                           'manual' => \$man,
                           'debug' => \$debug)
            or pod2usage(2);
    if ( $man or $help ) {
        # Load Pod::Usage only if needed.
        require "Pod/";
        import Pod::Usage;
        pod2usage(1) if $help;
        pod2usage(VERBOSE => 2) if $man;

Pod::Usage is available at The latest version of Getopt::Long (2.17 as of this writing) can be found in authors/Johan_Vromans. This kit also contains a script template that uses both Getopt::Long and Pod::Usage.


A few other option handling modules can be found on the CPAN. The following modules can be downloaded from



Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy


War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes


Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law


Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D

Copyright © 1996-2020 by Softpanorama Society. was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case is down you can use the at


The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March 12, 2019