Broad Network


Writing a Perl Command Line Tool

Command Line Software - Part 1

Perl Course

Foreword: In this article I explain how to write a command line tool

By: Chrysanthus Date Published: 14 Apr 2015

Introduction

A command line tool is an interface program between the console and an application (or large program). In this article I explain how to write a command line tool. When do you need a command line tool? For applications where commands are issued, one at a time! For teaching the use of an application! For illustrative applications such as University Computer Science projects! For illustrative applications for seminars! You should have basic knowledge in Perl in order to understand this article.

It is actually simple to write a Perl command line tool. You might have heard the word application above and maybe you cannot write an application, and you are probably thinking that since you cannot write an application, so you cannot write a command line tool. That is a mistake you are making if you are thinking like that. You are not the only one who would make such a mistake. As you will see below, it is so easy to write a command line tool, “that it will pull off your sucks”.

The article is divided into two phases: Basic Rules and Simple example. I use the Windows operating system and I am using drive C. If you are using a different operating system, then you will have to precede the file with something like, #!/usr/bin/perl .

I assume you know how to get the Perl interpreter running in your computer; so I will not address that issue here.

Basic Rules
Type the following code exactly and save it in the root directory with the name, cmndln.pl .

use strict;

    my $input;

    while (1)
        {
            print "Mysql>";
            $input = <STDIN>;
            $input =~ s/\s*;\s*$//;
            $input =~ s/^\s*//;

            print $input, "\n";

            if ($input =~ /quit/i)
                {
                    print "Bye", "\n";
                    last;
                }
        }

Go to the console (command prompt) and at the root directory, type the following and press the Enter Key:

    cmndln.pl

You should see, Mysql> which is the command prompt of the tool (the cmndln.pl file).

Type anything at this prompt and press the Enter Key.

You should see, what you have typed, redisplayed. You should still see the tool prompt. To quit the tool, type the following and press the Enter Key:

    quit

You should see the word, “quit” redisplayed and below it you should see, Bye; then the DOS prompt. At this point, you have quitted the command line tool and the tool is no longer operating.

Explanation of Basic Rules
I now explain the above code, stressing on the relevant rules. The code begins with, “use strict;”. Always use this line in your Perl script to avoid ambiguity. The next line is the declaration of the variable, $input. This variable will hold anything that you type as input. Input to a command line tool is a line of text ending with the newline (\n) character. The \n character comes in, as a result of the fact that you press the Enter Key.

After that you have the while loop. The condition of the while loop is (1). This means it should iterate infinitely, unless some condition occurs within the loop (square brackets), to break the loop.

The first line in the square brackets is “print "Mysql>";”, which prints the command prompt for the tool. While the tool is running, this prompt replaces the DOS prompt. When the tool stops running, you get back your DOS prompt.

After the command prompt for the tool has been printed, and while in the while loop, execution goes to the line, “$input = <STDIN>;” . Whenever execution of a program reaches a statement like this, the execution halts, and you see a flashing underscore, on the right of the tool prompt. <STDIN> in Perl means, whenever text (short or long) is typed at the tool prompt, and the Enter Key pressed, <STDIN> should return the complete text including the key that represents the Enter Key, i.e. \n to the variable it is assigned to. In this case, the variable it is assigned to is, $input.

In practice, the end of the input text may have ‘;’ and space before or after ‘;’. All input text end with \n. The input text is a string. The next line in the code, “$input =~ s/\s*;\s*$//;” removes any space, any ‘;’ and any \n at the end of the input string. The line following, removes any space at the beginning of the input string. Such spaces are accidentally typed in by the user.

The next line, “print $input, "\n";” displays the input text without any unnecessary delimiting characters.

Now, because of the condition, (1) of the while loop, the while loop should iterate infinitely. However, when the user types “quit” without the quotes, at the tool prompt, the last code segment will break the while loop and put an end to the running of the program. It does this as follows:

The last code segment in the while loop is an if-statement. The condition of the if-statement is, “$input =~ /quit/i”. This checks whether the input text is, “quit”, letter casing does not matter. If it is, then the loop has to be broken. In Perl, you break a loop with the statement, “last;”. Before “last;” is executed, the string, “Bye” is printed.

Yes, I told you it was easy; that is right. It is simple! Above are the basics of producing a Perl command line tool. Below, I give you a simple example related to a practical program (tool).

Simple Example
The simple example is the minimum program or command line tool, to access the MySQL server. Now, a database is software that keeps data in an organized fashion. A server, is software that creates and maintains the database. MySQL is an example of a database server. The server can work with a module (file) called, Mysql.pm . This module is written in Perl. This module has functions and variables, used to send and received data from the MySQL server (and database). Your command line tool, is a console program that uses the functions and variables of the module. The user, uses the command line tool.

This simple tool can do three main things. It can connect to the server; it can close the connection; and it can send database instructions know as SQL statements, to the server.

The connection command is a function without parentheses, and may or may not end with a semicolon. The close connection command is also a function without parentheses, and may or may not end with a semicolon. A SQL statement must end with a semicolon. However, the server does not need the ending semicolon, so the command line tool (program) strips it off.

I now present the program code, and its explanation:

use strict;
use Mysql;

    my $input;
    my ($user, $password, $domain, $port);

    while (1)
        {
            print "Mysql>";
            $input = <STDIN>;
            $input =~ s/\s*;\s*$//;
            $input =~ s/^\s*//;

            if ($input =~ /^connect/i)
                {
                    $input =~ s/^connect\s*//i;  
                    ($user, $domain, $port) = split (/(?:,\s*)/, $input);
                    $user =~ s/'//g;  $user =~ s/"//g;  $domain =~ s/'//g;  $domain =~ s/"//g;
                    print "Password: ";
                    $password = <STDIN>;
                    chomp($password);

                    if (!Mysql::connect($user, $password, $domain, $port))
                        {
                            print $Mysql::Error_msg, "\n";
                        }
                    else
                        {
                            print "Connection made.\n";
                        }
                }
            elsif ($input =~ /^close/i)
                {
                    $input =~ s/^close\s*//i;
                    if (!Mysql::close())
                        {
                            print $Mysql::Error_msg, "\n";
                        }
                    else
                        {
                            print "Connection closed.\n";
                        }
                }
            else
                {
                    if ($input !~ /quit/i)
                        {
                            if (!Mysql::query($input))
                                {
                                    print $Mysql::Error_msg, "\n";
                                }
                            else
                                {
                                    print "Query OK. ", "\n";
                                }
                        }
                }

            if ($input =~ /quit/i)
                {
                    print "Bye", "\n";
                    last;
                }
        }

First you have the “use strict;” statement. This statement should always be there. Next you have, “use Mysql;”. The Perl file, Mysql.pm has the functions and variables to be used by the command line tool. So, this statement brings in the module, Mysql.pm into the command line tool program. The program (tool) can then use the functions and variables by just preceding a function or variable with “Mysql::”

The next code segment in the script (program) has the $input variable declared and four new variables. The $input variable here, has the same use as mentioned above. In order to connect to the server, you need the variables, $user for user name, e.g. "root", $password for password, e.g. "sql", $domain for domain name, e.g. "yahoo.com" and $port for a number, e.g. 3306 . These variables are declared in the segment.

Next, you have the while loop. Everything else is in the while loop. The first code segment in the while loop is the same as for the basic code above and has the same meaning; so I will not talk about that here. The last code segment in the while loop is the same as for the basic code above; it is for quitting, and has the same meaning; so I will not talk about that here.

The second code segment in the while block, is the if-part of an if-elsif-else construct. It has two segments. This if-part checks if input text is a connect function. If it is, then its first segment obtains, $user, $domain and $port values. The connect function can be something like the following, typed by the user:

    connect "root", "localhost", 3306

When this is typed, and the Enter Key pressed, the complete string with the ending \n should be the value of the $input variable. The split() function in the first code segment of the if-part, splits this string and assigns the relevant values to the variables, $user, $domain and $port. This first code segment also receives the password e.g. "sql\n" and assigns it to the variable, $password. It also removes the newline character, \n but this time with the statement, “chomp($password);”.

The second code segment in the if-part attempts the connection with the pure variables, $user, $password, $domain and $port. If the connection is not successful, in the Mysql.pm file, an error message will go into the Error_msg variable and the command line tool will print this error message with the statement, “print $Mysql::Error_msg, "\n";”. Otherwise, the connection was successful and the segment will print, “Connection made.”.

To close the connection, the user will type:

    close

The elsif block in the while loop handles this action to close the connection. The explanation of this block is similar to that of the connect function.

The main purpose of the command line tool is to be sending SQL statements to the server, one after the other. The Mysql.pm file has a function called, query(). The argument to this function is the SQL statement. The else block of the if-elsif-else construct handles the SQL statement. The explanation of the block, is similar to the connect, and close code segments.

Note from the above code, that the Mysql.pm file has the functions, connect(), close() and query(). connect() is for connecting to the server; close() is for closing the connection and query() is for sending SQL statements to the server.

That is it, for writing a Perl command line tool. There may be features in the simple example code that you do not understand. You do not have to understand them, unless you want to be programming the MySQL server. If you want to be programming the free MySQL server, then the link to the complete and free Perl-MySQL command line tool, is given below.

Chrys


PurePerl MySQL Command Line Tool

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

Comments

Become the Writer's Fan
Send the Writer a Message