Warning: preg_replace(): Compilation failed: escape sequence is invalid in character class at offset 4 in /home/customer/www/theunixtips.com/public_html/wp-content/plugins/resume-builder/includes/class.resume-builder-enqueues.php on line 59

perl : Process Command Line Arguments

GetOpt module in perl provides a very easy way to process the command line arguments. It also performs the type check. Here is a sample snippet that I use very often.

use Getopt::Long;

#Process command line arguments
$result = GetOptions(
	"port=i"	=> $Port,
	"host=s"	=> $Host,
	"interval=f"	=> $Interval,
	"random!"	=> $Randomize,
	"h"		=> $Help
);

The type after the equal “=” sign dictates the type of variable that is expected. This is very helpful because the module will perform the type checking and ensure that it receives what is expected. For example if you try to give –port “abcd” it will fail that an integer is expected. Read on for a brief explanation of types.

Flag Type Example
i integer –port 80
s string –host www.yahoo.com
f float –interval 1.5
none none No value will be required. Used for flags that don’t require a value. For example boolen variables like -h for help or -v for printing version or -d for debug and so on…..

It also supports the negation flag “!” for boolen variables, which means that either the flag can be used as is or it can be prefixed with “no” to disable the flag. In my example earlier I specify “random!” which means if –random is provided it will mark my boolen variable $Randomize true and if –norandom is provided it will mark the same variable as false.