Messed with Getopt::Long

Today I had to fix some old test automation code where in a perl script functions of flush.pl and getopts.pl were getting used and scripts were failing on RHEL7 as these are the old and obsolete legacy libraries of perl.

The solution was to replace function Getopts (belongs to getopts.pl) with function GetOptions (belongs to Getopt::Long perl module). Call to Getopts is relatively very different than GetOptions. Though the purpose remains very similar. We can say it is the extended version of Getopts.

Basically, the purpose of GetOptions() is to parse the command line parameters. It also checks the type of arguments. It returns true or false depending on arguments processed successfully or not.

Here is the example how I used it in my test automation ::

Files :: 1. Test.sh 2. Customer.pl

Calling my perl script (Customer.pl) in my Shell script (Test.sh):: perl Customer.pl -u 100 -f Customer.ldif

Parsing Arguments in Customer.pl (argument -u and -f)::

#Loading the module
use Getopt::Long;

#set up local defaults
my $Number_Users = 1;
$Output_File = “output.ldif”;

#no values options, True if present in the argument list else false
$Verbose = 0;
$Append = 0;

#Assigning the actual values by parsing the arguments in call
GetOptions(‘u=i’     => \$Number_Users,
‘f=s’     => \$Output_File,
‘verbose’     => \$Verbose,
‘Append’     => \$Append,
);

So now I have the values Number_Users=100 and Output_File=Customer.ldif. Here meaning of i in ‘u=i’ is that the argument value of option -u must be an integer and meaning of s in ‘f=s’ is argument value of option -f must be a string.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s