Perl - Command Line Options

From Torben's Wiki
Jump to: navigation, search

Help: Cpan Nice Article

use Getopt::Long;
my %o; # stores command line parameters/options
$o{'trans'} = 1; # defaults
$o{'gray' } = 0;
my $res = GetOptions (\%o, "trans|t!", "trim!", "gray|grey|g!"); 
# simple flag: 1/0
$debug = 0; # set default value for option
$result = GetOptions ("debug" => $debug);  
print "Debug flag is $debug";
# ./script.pl --debug

# read options
$result = GetOptions ("age=i" => $age);
# i for int ; s for string
if ($age) { print "Input age is $age years"; }
# ./script.pl --age=89

# optional options
# use ":" instead of "="
$result = GetOptions ("age:i" => $age)

# multiple names for one option
$result = GetOptions ("color|colour|c" => $color);  

# yes / no value
$counter = -1;  # default value
$result = GetOptions ("counter!" => $counter);
# ./script.pl --counter
-> Counter is 1
# ./script.pl --nocounter
-> Counter is 0

# hashing it
%options = ();
$result = GetOptions (\%options, "base=i", "height=i");  
print $options{'base'};
Personal tools