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

Wednesday, February 10, 2010

vim command to delete lines

My fingertips know the command to delete all the lines starting from current line till EOF (that's d + shift g) but I rarely remember the command to delete all the lines up to head of the file.

Luckily, vim offers a simple approach to delete desired lines, all we need to be aware is the following
  • . (dot) - represents current line
  • $ - represents EOF
  • syntax: start_line_num,end_line_num vim_cmd
Some example usages (Note: these commands are run in the editor, hence the beginning colon)
  • Delete all the lines starting from current line : .,$ del
  • Delete lines starting from 1 to so far : 1,. del
  • Delete all lines between 10 and 25 (inclusive) : 10,25 del
  • Delete all lines between 10 and 25 (inclusive) : 10,+14 del
  • Delete next 15 lines including the current : .,+14 del
  • Delete last 15 lines including the current : .,-14 del