Being able to parse perl options in a user-friendly manner is not immediately obvious task but it is quite easy thanks to the built-in Perl library Getopt. Getopt is a very robust function with lots of options -- see the official documentation for an exhaustive manual. This article will serve as a crash-course for quickly using Getopt to obtain both boolean and value-oriented options.
Let's begin by supposing we want to parse the following options in a script like so:
my_script_name.pl -foo -bar "Hello world!" my_script_name.pl -f -b "Hello world!"
First, include the library and declare the variables where your option values will reside (use of strict is assumed here).
1 2 3 4 |
use Getopt::Long; my $foo; my $bar; |
In this example, foo is a switch (we are only interested if the switch exists or not), and bar is an option which includes some value. Now we will call GetOptions, which will actually parse the command line and retrieve these values:
5 6 7 |
die unless GetOptions ( "f|foo" => \$foo, "b|bar=s" => \$bar, ); |
The letter before the | symbol indicates the shorthand name for the option, the word following it is the full switch name. The "=s" addition on the bar indicates that this option takes a string as a parameter. Now, our variables hold the values! Below is an example where we print the message passed in using bar, and then print an additional message if the foo switch is passed in.
8 9 10 11 |
print $bar."\n"; if($foo){ print "Foo switch received!\n"; } |
You can easily check if an option exists or not by checking if it is defined. For instance, if bar was a necessary option, we can do the following:
Now let's put it all together!





