Perl: Command Line Options Without GetOpt::Std

Summary:

At times you may need to write a script that needs to be completely portable. Meaning, you can't rely on modules that may not be included stock with the operating system.

On Redhat, GetOpt::Std is not included in the stock installation (at least not where I work). Therefore, I needed just a quick and simple way to parse command line options into the script.

The following is an example 'test.pl' of how I did this:

#!/usr/bin/perl -w

use strict;

my $ip_address;
my $mac_address;
my $hostname;
my $debug = 0;

# Sort the options
while (@ARGV) {
  if($ARGV[0] eq '-h' || $ARGV[0] eq '--help') {
    shift(@ARGV);
    &display_help;
    exit;
  }
  if($ARGV[0] eq '-i' || $ARGV[0] eq '--ip') {
    shift(@ARGV);
    $ip_address = shift(@ARGV); 
    next;
  }
  if($ARGV[0] eq '-m' || $ARGV[0] eq '--mac') {
    shift(@ARGV);
    $mac_address  = shift(@ARGV); 
    next;
  }
  if($ARGV[0] eq '-H' || $ARGV[0] eq '--hostname') {
    shift(@ARGV);
    $hostname       = shift(@ARGV); 
    next;
  }
  if($ARGV[0] eq '-D' || $ARGV[0] eq '--debug') {
    shift(@ARGV);
    $debug       = 1; 
    next;
  }
}

sub display_help() {
  my $option      = '';
  my $description = '';
  my %help_menu   = ();

  print "\n";
  print "USAGE:\n\n";
  print "./test.pl -(OPTION) <VALUE>\n\n";
  print "OPTIONS:\n\n";
  format STDOUT =
    @<<<<<<<<<<<    @<<<<<<<<<<<<<<<<<<<<<<<<
    $option,        $description
.

  %help_menu = (
    '-h,--help'     =>  'display help',
    '-i,--ip'       =>  'ip address',
    '-m,--mac'      =>  'mac address',
    '-h,--hostname' =>  'hostname',
    '-D,--debug'    =>  'toggle debug info'
  );

  foreach(keys %help_menu) {
    $option = $_;
    $description = $help_menu{$_};
    write();
  }

  print "\n\n";
}

print "IP Address  : $ip_address\n";
print "MAC Address : $mac_address\n";
print "Hostname    : $hostname\n";




New comers to Perl may need to reference the Array data type and Shift documentation to clarify the situation.

Now, lets see what it looks like:




[wdierkes@dev ~]$ ./test.pl --help

USAGE:

./test.pl -(OPTION) <VALUE>

OPTIONS:

    -m,--mac        mac address
    -D,--debug      toggle debug info
    -h,--help       display help
    -h,--hostnam    hostname
    -i,--ip         ip address


[wdierkes@dev ~]$ ./test.pl -H test.example.com \
                            --ip 192.168.0.102 \
                            --mac 00:5b:18:43:1n:9c

IP Address  : 192.168.0.102
MAC Address : 00:5b:18:43:1n:9c
Hostname    : test.example.com