APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

Perl Getopt and GetOptions


© September 2003 Tony Lawrence
September 2003

Two Perl modules (Getopt and Getoptions::Long) work to extract program flags and arguments much like Getopt and Getopts do for shell programming. The Perl modules, especially GetOptions::Long, are much more powerful and flexible.

Simple scripts show the power of these:

#!/usr/bin/perl
# script is "./g"
use Getopt::Std;
%options=();
getopts("od:fF",\%options);
# like the shell getopt, "d:" means d takes an argument
print "-o $options{o}\n" if defined $options{o};
print "-d $options{d}\n" if defined $options{d};
print "-f $options{f}\n" if defined $options{f};
print "-F $options{F}\n" if defined $options{F};
print "Unprocessed by Getopt::Std:\n" if $ARGV[0];
foreach (@ARGV) {
  print "$_\n";
}

Trying it out:

bash-2.05a$ ./g  -f -d F -o -F
-o 1
-d F
-f 1
-F 1
bash-2.05a$ ./g -o -d foo
-o 1
-d foo
bash-2.05a$ ./g -o rough -d foo
-o 1
Unprocessed by Getopt::Std:
rough
-d
foo
 

Processing of arguments stops when it saw "rough".

If you leave off a required argument, it just gets swallowed:

bash-2.05a$ ./g -d
bash-2.05a$ ./g -d foo
-d foo
 

But it's easily confused:

bash-2.05a$ ./g -d -o -f       
-d -o
-f 1
 

It thinks that -o is the argument of -d.

bash-2.05a$ ./g -k    
Unknown option: k
 

Like the simple shell "getopt", this complains when it gets an option that it doesn't know about. Unlike the shell "getopt", prefacing the option string with a ":" doesn't help. Instead, use "getopt":

#!/usr/bin/perl
# we'll call this one ./gg
use Getopt::Std;
%options=();
getopt("odfF",\%options);
print "-o $options{o}\n" if defined $options{o};
print "-d $options{d}\n" if defined $options{d};
print "-f $options{f}\n" if defined $options{f};
print "-F $options{F}\n" if defined $options{F};
 

Note the lack of any ":". This module doesn't care which flags take values and which don't: it assumes ALL of them take arguments.

The "getopt" isn't very bright:

bash-2.05a$ ./gg -f -o -d foo 
-d foo
-f -o
bash-2.05a$ ./g -f -o -d foo 
-o 1
-d foo
-f 1
 

But it doesn't complain:

bash-2.05a$ ./gg -l
bash-2.05a$ ./g -l
Unknown option: l

Unlike their shell cousins, neither of these have any issues with arguments containing spaces:


bash-2.05a$ ./g -o  -d "foo bar"          
-o 1
-d foo bar
bash-2.05a$ ./gg -o "foo"  -d "foo bar" 
-o foo
-d foo bar
 

Far better than either of these is the Getopt::Long module. Here's a script to play with it:

#!/usr/bin/perl
use Getopt::Long;
GetOptions("o"=>\$oflag,
            "verbose!"=>\$verboseornoverbose,
            "string=s"=>\$stringmandatory,
            "optional:s"=>\$optionalstring,
            "int=i"=> \$mandatoryinteger,
            "optint:i"=> \$optionalinteger,
            "float=f"=> \$mandatoryfloat,
            "optfloat:f"=> \$optionalfloat);
print "oflag $oflag\n" if $oflag;
print "verboseornoverbose $verboseornoverbose\n" if $verboseornoverbose;
print "stringmandatory $stringmandatory\n" if $stringmandatory;
print "optionalstring $optionalstring\n" if $optionalstring;
print "mandatoryinteger $mandatoryinteger\n" if $mandatoryinteger;
print "optionalinteger $optionalinteger\n" if $optionalinteger;
print "mandatoryfloat $mandatoryfloat\n" if $mandatoryfloat;
print "optionalfloat $optionalfloat\n" if $optionalfloat;

print "Unprocessed by Getopt::Long\n" if $ARGV[0];
foreach (@ARGV) {
  print "$_\n";
}
 

The hash array that this uses holds the argument name and the type of argument; what that points to is where it will store values for options processed.

Playing with it:

#
# doesn't care if it's -o or --o
bash-2.05a$ ./ggg -o
oflag 1
bash-2.05a$ ./ggg --o
oflag 1
#
# abbreviating is ok too
bash-2.05a$ ./ggg -verbose
verboseornoverbose 1
bash-2.05a$ ./ggg -verb   
verboseornoverbose 1
#
# but not this
bash-2.05a$ ./ggg -verbosity 
Unknown option: verbosity
#
# $verboseonoverbose will be 0 here
bash-2.05a$ ./ggg -noverb
#
# strings
bash-2.05a$ ./gggg -s    
Option string requires an argument
bash-2.05a$ ./ggg -s=foo
stringmandatory foo
bash-2.05a$ ./ggg -optional
bash-2.05a$ ./ggg -optional=foo
optionalstring foo
#
# ambiguity
bash-2.05a$ ./ggg --opt     
Option opt is ambiguous (optfloat, optint, optional)
#
# floats and integers
bash-2.05a$ ./ggg --optfloat=75.6
optionalfloat 75.6
bash-2.05a$ ./ggg --optint=75.6
Value "75.6" invalid for option optint (number expected)
bash-2.05a$ ./ggg --optint=75  
optionalinteger 75
bash-2.05a$ ./ggg -f --optfloat=75.6 -o
Value "--optfloat=75.6" invalid for option float (real number expected)
oflag 1
# once it runs out of options, it leaves @ARGV alone:
bash-2.05a$ ./ggg -o foo bar
oflag 1

Unprocessed by Getopt::Long
foo
bar

GetOpt::Long is obviously much more flexible. The hash you pass is a little clumsy, but if you think about it, there's no better way to do it. In some places, you might use something like this:

#!/usr/bin/perl
use Getopt::Long;
my %moo=();
GetOptions("o"=>\$moo{$oflag},
            "verbose!"=>\$moo{verbose},
            "string=s"=>\$moo{stringmandatory},
            "optional:s"=>\$moo{optionalstring},
            "int=i"=> \$moo{mandatoryinteger},
            "optint:i"=> \$moo{optionalinteger},
            "float=f"=> \$moo{mandatoryfloat},
            "optfloat:f"=> \$moo{optionalfloat});

foreach (keys %moo) {
 print "$_ = $moo{$_}\n";
}

print "Unprocessed by Getopt::Long\n" if $ARGV[0];
foreach (@ARGV) {
  print "$_\n";
}
 

but if you have so many flags that you are thinking that is helpful, your program is surely trying much too hard to be all things to all people.


Got something to add? Send me email.





(OLDER)    <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

->
-> Perl Getopt and GetOptions

16 comments


Inexpensive and informative Apple related e-books:

iOS 10: A Take Control Crash Course

Take Control of Upgrading to El Capitan

Photos for Mac: A Take Control Crash Course

Take Control of Apple Mail, Third Edition

Sierra: A Take Control Crash Course




More Articles by © Tony Lawrence


" but if you have so many flags that you are thinking that is helpful, your program is surely trying much too hard to be all things to all people."

Isn't that the philosophy behind Windows development? <Grin>

After reading through all this, I said to myself, "One of these days I have to become an expert in Perl." <Smile>

I have to admit that I'm much more likely to turn to a shell script or C to do a lot of the things that Perl would probably be better suited to doing. In many cases, a Perl program would certainly involve less work than writing and compiling a C program, and would undoubtably be more elegant and efficient than a typical shell script. However, as with using greenbar paper, old habits are hard to shake. I grok C and the shell, whereas I'm a rank amateur when it comes to Perl. One of these days...

--BigDumbDinosaur

The nice thing about Perl is that you don't have to be anything close to an expert to have it be helpful. If you know awk and sed and a little sh or ksh, you already understand a lot of Perl without even knowing it yet.

See https://aplawrence.com/Unixart/loveperl.html

--TonyLawrence



---September 18, 2004


I recently resumed perl programming after a ten year hiatus;
yup, just like riding a bike - I was really suprised how much perl lore lay dormant in the deep recesses of my aging brain. It has been a boon in refining a nascent automated java build framework I unexpectedly inherited. Combing ant, cruisecontrol, java, ksh, and perl, I was able to produce a flexible production grade build process in a matter of days... Getopts::Long was instrumental in enabling the central build.pl program to flexibly support any flavour of build one can imagine.
--Fleh

---February 10, 2005
SO how would I define the vars when I want to use-strict ? When I put it in I get:
Global symbol "$oflag" requires explicit package name at ./tester.pl line 5.
Global symbol "$verboseornoverbose" requires explicit package name at ./tester.pl line 6.
...etc. etc

Which is easy to fix with normal vars but I don't know how with references in this context! Help appreciated.

--Scary B.


---February 10, 2005

Just like usual:

my $oflag;
my $verboseornoverbose;

etc.

--TonyLawrence







Wed May 4 00:00:32 2005: 441   Dave


test_opts2.pl -optional test
Use of uninitialized value in hash element at /home/dmckeon/scripts/test_opts2.pl line 11.
optionalstring = test

Program
**********************************************
#!/usr/bin/perl -w
# Option test dm


use strict;
use Getopt::Long;
my moo=();
my $oflag;


GetOptions("o"=>\$moo{$oflag},
"verbose!"=>\$moo{verbose},
"string=s"=>\$moo{stringmandatory},
"optional:s"=>\$moo{optionalstring},
"int=i"=> \$moo{mandatoryinteger},
"optint:i"=> \$moo{optionalinteger},
"float=f"=> \$moo{mandatoryfloat},
"optfloat:f"=> \$moo{optionalfloat});

foreach (keys moo) {
if ( defined $moo{$_} && exists $moo{$_}) {
print "$_ = $moo{$_}\n";
}
}

print "Unprocessed by Getopt::Long\n" if $ARGV[0];
foreach (@ARGV) {
print "$_\n";
}







Wed May 4 10:28:54 2005: 445   TonyLawrence

gravatar
Don't use -w or define your variables. Simple as that.



Mon Sep 12 18:51:10 2005: 1081   anonymous


-optional is the same as -o -p -t -i -o -n -a -l. You should use --optional.



Wed Jan 4 01:08:18 2006: 1474   Kika


The reason is probably the typo where '$oflag' should be just 'oflag'.



Tue Dec 11 06:42:22 2007: 3314   Gene


Uh. It's "GetOpt::Std" not "Getopt:Std" and "GetOpt::Long" not "Getoptions::Long"

You obviously never actually ran this code.

It is dishonest to publish something as "Information and Resources" that has blatant errors and is untested (and would never work).

In syntax, spelling is important.

Hope this helps,

Gene



Tue Dec 11 06:43:58 2007: 3315   gene


heh. Ok. "Getopt" not "GetOpt" as I thought. Maybe I need to relax some... ;)



Tue Dec 11 11:44:24 2007: 3316   TonyLawrence

gravatar
Who never ran the code, Gene?

:-)

Hey, we all do make typo's, But I usually cut and paste from working code. Not that I can't screw it up later with editing, of course..



Fri Jan 4 15:35:02 2008: 3388   anonymous


do the vars have to be defined as:
my $oflag;
etc.....
I already have vars in a hash and when I try to do something like this:
GetOptions ( "root=r" => \$conf->{root},
"cl=c" => \$conf->{client_name});
I get this error:
Error in option spec: "root=r"
Error in option spec: "cl=c"










Fri Jan 4 15:49:52 2008: 3389   TonyLawrence

gravatar
Send me your actual code in email; I'll take a look at it..



Fri Jan 4 16:21:09 2008: 3391   anonymous


Sorry I did not realize about the fees..Thanks Anyways.



Fri Jan 4 16:49:34 2008: 3392   anonymous


I figured it out.... wrong option specifiers. Amazing how syntax plays so much into programming and without knowing the correct one will drive u crazy. Logic is overrated!! : )
Thanks



Tue Jul 8 17:01:11 2008: 4400   Elden


This it my current method for handling 'default' values. Is there a cleaner way?

####### set up the defaults..........
my @file = ("CDN_DD.csv","PPDN_DD.csv");
my $unit =$ENV{"${pn}__LRU" } || "LSU_uP1";
my $numVarThresh =$ENV{"${pn}__PRINT_VAR_THRESH" } || 5;
my $w =$ENV{"${pn}__PRINT_VAR_WIDTH" } || -60;
my $na ="n/a";
my $help =0;
GetOptions( "lru=s" , \$unit
,"print_var_thresh=i" , \$numVarThresh
,"print_var_width=i" , \$w
,"na" , \$na
,"help" , \$help
);
if($help){usage();}
if(scalar(@ARGV)>0){@file=@ARGV;}

And how do you post <code> font to this site?







Thu Jul 2 09:50:58 2009: 6591   hemant

gravatar
Thanks for explanation by wonderful examples.



Wed Feb 9 04:18:28 2011: 9288   PhilGoetz

gravatar


I've used GetOpt::Long many times. I'm trying to use it on my Windows XP Cygwin system now, and it quite mysteriously will not run.
Help?

$ perl -e 'use GetOpt::Long; &GetOptions( "t=s" => $T)'
Undefined subroutine &main::GetOptions called at -e line 1.

$ cpan GetOpt::Long
CPAN: Storable loaded ok (v2.20)
Going to read '/home/brak/.cpan/Metadata'
Database was generated on Tue, 08 Feb 2011 22:42:11 GMT
Warning: Cannot install GetOpt::Long, don't know what it is.
Try the command

i /GetOpt::Long/

to find objects with matching identifiers.
CPAN: Time::HiRes loaded ok (v1.9719)

$ cpan

cpan shell -- CPAN exploration and modules installation (v1.9402)
Enter 'h' for help.

cpan[1]> i /GetOpt::Long/
CPAN: Storable loaded ok (v2.20)
Going to read '/home/brak/.cpan/Metadata'
Database was generated on Tue, 08 Feb 2011 22:42:11 GMT
Module = Getopt::Long (JV/Getopt-Long-2.38.tar.gz)
Module Getopt::Long::Descriptive (RJBS/Getopt-Long-Descriptive-0.089.tar.gz)
Module Getopt::Long::Descriptive::Opts (RJBS/Getopt-Long-Descriptive-0.089.tar.gz)
Module Getopt::Long::Descriptive::Usage (RJBS/Getopt-Long-Descriptive-0.089.tar.gz)
Module Getopt::Long::GUI (HARDAKER/Getopt-Long-GUI-0.1.tar.gz)
Module Getopt::Long::String (N/A)
Module Getopt::LongUsage (RGLAUE/Getopt-LongUsage-0.10.tgz)
Module POD2::IT::Getopt::Long (ENRYS/POD2-IT-Getopt-Long-1.02.tar.gz)
8 items found

cpan[2]> install GetOpt::Long
Warning: Cannot install GetOpt::Long, don't know what it is.
Try the command

i /GetOpt::Long/

to find objects with matching identifiers.
CPAN: Time::HiRes loaded ok (v1.9719)



Tue Feb 26 19:31:13 2013: 11912   spetry

gravatar


What I had trouble finding documentation on is how to use Getopt::Long to use multiple flags for the same variable. Example: -host sets the same variable as -hostname, or -m sets the same name as -mac. Sure, I could use a hash or array to do the same thing, but this is a piece of specific code to populate a DB with data. Sometimes easier logic is required for debugging.

$IP ='';
$MAC = '';
$HOST = '';
$Serial = '';

GetOptions('i|ip|address=s',\$IP,
'n|host|hostname=s',\$HOST,
's|serial=s', \$Serial,
'm|mac=s', \$MAC);

In the above, -n -host and -hostname will all populate the IP variable with the arg (-h is reserved if you are asking why "-n" instead of "-h"). Similarly, -m and -mac are identical for how GetOptions().



Tue Feb 26 20:46:45 2013: 11913   TonyLawrence

gravatar


Thanks!

------------------------


Printer Friendly Version

Have you tried Searching this site?

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us


Printer Friendly Version





Perl is designed to give you several ways to do anything, so consider picking the most readable one. (Larry Wall)




Linux posts

Troubleshooting posts


This post tagged:

Code

Perl

Popular

Programming



Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode