Archive

Posts Tagged ‘command line options’

Perl – getOpt for retrieving command line options


If you are writing a perl script that you wish to take in arguments from the command line then you will need to use the getOpt function.

GetOpt variations

There are two versions of getOpt with perl. You can either use GetOpt::Std which will process single character switches, or you can use GetOpt::Long which will process single character switches, as well as fullname –word switches.

Getopt::Long Examples

The below example shows how a command line switch can be used:

---perl script (disc.pl)---
use warnings;
use strict;
use Getopt::Long;
my $DISC;
GetOptions (
'disc|d=s' => \$DISC
);
print "DISC = $DISC\n";

To run the script you enter the following at the command line:

$ ./disc.pl -d C

or

$ ./disc.pl --disc C

Both of these commands will pass the value “C” to the parameter “DISC”. The script will then print the value of $DISC to the screen.

The =s means that the option is a required arbitary value, if it were :s instead that would mean it is an optional arbitary value. Without the s the value is either 0 or 1 according to whether the option has been used on the command line.

If the value is a numeric you can use the i flag instead of the s flag.

Advertisements