Oct 18, 2012

PERL Script with command line options

It's been a long time since I have done a tutorial about PERL scripting, so I cracked my fingers and got down to hacking some code to create a basic command line script with options.

To give you an idea, I want to be able to run a command and pass some optional flags to it. For instance:

perl-script -h -username nassar

It turns out that this is a very simple thing to do because PERL has an inbuilt getopts function.

#!/usr/bin/perl -w
#
# This is a perl script that uses warnings (hence the -w flag)
#
# This perl scripts is a test of the getopts function

# Use strict perl
use strict;

# Use the Getopt library
use Getopt::Std;

# Creates a hash variable where we can store our command line options
my %options=();

# Grab the list of command line options (some with optional arguments,
#   denoted by a ':')
#   -u {username}   : Sets the username
#   -p {password}   : Sets the password
#   -H {hostname}   : Sets the hostname
#   -D {database}   : Sets the database
#   -h              : Displays the help
#   -d              : Debugging
getopts("hdu:p:H:D:", \%options);

# Sets some variables based on command line options, otherwise use defaults
my $username = (defined $options{u}) ? $options{u} : 'test';
my $password = (defined $options{p}) ? $options{p} : 'test';
my $hostname = (defined $options{H}) ? $options{H} : 'localhost';
my $database = (defined $options{D}) ? $options{D} : 'testdb';

# Output the display menu if asked for
if (defined $options{h}) {
    print "The '-h' flag was invoked\n\n";
}

# Output the display menu if asked for
if (defined $options{d}) {
    print "The '-d' flag was invoked\n\n";
}

print "USERNAME: " .$username . "\nPASSWORD: " . $password . "\nHOSTNAME: " . $hostname . "\nDATABASE: " . $database . "\n\n";

exit 0;

 Make sure the script is set to be executable and you will get output similar to the following:

nassar@computer:~$ ./test.pl -u test -d -h
The '-h' flag was invoked

The '-d' flag was invoked

USERNAME: test
PASSWORD: testslair
HOSTNAME: localhost
DATABASE: testslairdb

nassar@
computer:~$

References:

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!