Friday, April 02, 2010

Perl HowTo: Parsing command line options

Sample program to work with CLI options. Play with this program options and pay
attention to the reported usage errors to better understand how GetOptions() work.

# CODE STARTS HERE
#!perl -w

=head1
 Using GetOptions() to process CLI options
 Ref: http://perldoc.perl.org/Getopt/Long.html
=cut

# Required module
use Getopt::Long;
use strict;

my $grade = 'A';
my $pcile = 0.0;
my $name = '';
my $result = 0;    # Fail by default
my $promote = 0;
my @marks = ();
my %history = ();

sub show_usage()
{
   print "\nUsage: --name name --grade [A|B|C|D] --marks m1 m2 m3\n" .
                "       [--pass] [--promote | --nopromote]\n\n";
   exit( 0 );
}

if ( !scalar( @ARGV ) )
{
   show_usage();
}

if ( !GetOptions( 'name=s'       => \$name,       # =  - mandatory, string
                  'grade:s'      => \$grade,      # :  - optional, string
                  'percentile:f' => \$pcile,      # read float value
                  'marks=i{3}'   => \@marks,      # sequence of 3 numerals
                  'pass'         => \$result,     # optional, flag
                  'promote!'     => \$promote,    # -promote and -nopromote
                  'history:s{2}' => \%history ) ) # sequence of 2 strings
{
   show_usage();
}


print "\n    SUMMARY   \n\n";
print "Name      : $name\n";
print "Marks     : ";
foreach( @marks )
{
   print $_ . " ";
}

print "\n";
print "Grade     : $grade\n";
print "Percentile: $pcile\n";
print "Result    : $result\n";
print "Promote?  : $promote\n";
print "\n";
print "History : ";
foreach( keys( %history ) )
{
   print $_ . " = " . $history{$_} . "; ";
}
print "\n";

0;

# CODE ENDS HERE