New Users: Quick Perl CLI

Quick Perl (CLI) 3.5-Apollo

On the previous page I covered Perl CGI (common gateway interface) I now cover the second face of Perl CLI (command line interface. Perl CLI is easy to use, combine this with batch files and it provides unlimited power to manipulate files and system resources. Perl was originally designed for this very task it’s designers have retained this core functionality.

Perl's core component consists of two files; these are portable hence you can use them independently of Uniform Server. This portability you can use to great advantage, for the examples on this page I think it is best to move the Perl engine to a working folder if you wish you can use the existing Uniform Server’s location the choice is yours.

Perl Engine -Working folder

All we need to do is make a copy of the two files and place them in a working folder. You can use any drive and name the folder whatever you like. I tend to name my folders with a suffix a_ the only reason for doing this when viewed in Explorer brings them to the top of a folder tree. One tip keep your file and folder names short this saves you a lot of typing when using a command window.

Follow these instructions to create a working copy of Perl:

  1. On C drive create a new folder named a_perl
  2. Navigate to the folder *\Uniform Server\udrive\usr\bin
  • This contains the two files:
    perl58.dll (engine)
    perl.exe (interface)
  1. Copy the above two files to folder c:\a_perl

Interface file perl.exe is the “Perl Command Line Interpreter” it receives commands both from you (command prompt CLI) or another program (Apache CGI), decides on the appropriate action and returns information. A Perl script is passed to the main engine perl58.dll “Perl Interpreter” this compiles a script and returns the result via the interface back to you or the calling program.

Top

Test Script

This test script is as old as the hills, run Notepad (or any other text editor) and type the following line into it:

print "Hello World";

Save the file to folder c:\a_perl and name it test.pl

Note: All Perl scripts you write need to have a file extension of .pl

Top

How to run a command prompt

The following shows how to start a command prompt however unless you like typing I do not expect you to sit there using it full time. I have shown it to highlight the commands you need to type in.

These commands are important, they are used in batch files to make life easier I cover this later. Aldo shown is the method of running a PHP script.

  1. Start a command prompt Click Start > Click Run > Type in cmd click OK
    This opens a small black window referred to as the command prompt.
  2. Type the following commands into this window:
  • Type in cd .. press enter key – this takes you up one level in the folder tree
  • Type in cd .. press enter key – again takes you up one level
  • Display: C:\> - This is your top level on C drive if you type cd .. again you will go no further you are already at the top
  1. Type cd a_perl press enter - this changes the folder as indicated by the prompt c:\a_perl>
  2. Type dir press enter - this displays the folder content (the two files you copied to it)
  3. Type perl.exe -v and press return -- Perl information will be displayed.
  4. Type perl.exe test.pl press enter key
  5. Type pause press enter key -- this command results in "Press any key to continue . . ."
  6. Type exit press return -- this ends the command prompt

Those eight steps result in a display similar to this:

 

Steps 2 and 3: Are really demonstrating how to move up and down the folder tree. The two full stops move you up one level, while cd stands for change directory (folder) effectively moving you down the folder tree.

Step 5: Is of importance it shows how to pass a switch to Perl in this case display its version information. If you run the same line with –h switch it displays a whole host of switches you can use. I have highlighted the two I find most useful. Switches are predominately used when running Perl as CLI, normally never used in CGI other than via script commands.

These two I find most useful:

  • -c check syntax only (runs BEGIN and CHECK blocks)
  • -W enable all warnings

Switches are predominately used when running PHP as CLI here is the full list:

C:\a_perl>perl -h

Usage: C:\a_perl\perl.exe [switches] [--] [programfile] [arguments]
-0[octal] specify record separator (\0, if no argument)
-a autosplit mode with -n or -p (splits $_ into @F)
-C[number/list] enables the listed Unicode features
-c check syntax only (runs BEGIN and CHECK blocks)
-d[:debugger] run program under debugger
-D[number/list] set debugging flags (argument is a bit mask or alphabets)
-e program one line of program (several -e's allowed, omit programfile)
-f don't do $sitelib/sitecustomize.pl at startup
-F/pattern/ split() pattern for -a switch (//'s are optional)
-i[extension] edit <> files in place (makes backup if extension supplied)
-Idirectory specify @INC/#include directory (several -I's allowed)
-l[octal] enable line ending processing, specifies line terminator
-[mM][-]module execute "use/no module..." before executing program
-n assume "while (<>) { ... }" loop around program
-p assume loop like -n but print line also, like sed
-P run program through C preprocessor before compilation
-s enable rudimentary parsing for switches after programfile
-S look for programfile using PATH environment variable
-t enable tainting warnings
-T enable tainting checks
-u dump core after parsing program
-U allow unsafe operations
-v print version, subversion (includes VERY IMPORTANT perl info)
-V[:variable] print configuration summary (or a single Config.pm variable)
-w enable many useful warnings (RECOMMENDED)
-W enable all warnings
-x[directory] strip off text before #!perl line and perhaps cd to directory
-X disable all warnings

Step 6: Shows how to run your Perl script. Main point here you must specify the executable perl.exe you cannot just type in test.pl and expect it to run. We are running Perl in a portable environment; by this I mean Windows has no idea what to do with the file you typed in, since there is no Windows path to the executable and no file extension .pl association with any executable. If running a script from another folder not containing the executable (perl.exe) the full path to it must supplied. For example c:\a_perl\perl.exe some_script.pl

Step 7: I slipped this in to show you what a pause command displays; it stops execution and waits for a response from a user, absolutely not required when running interactively with a command window. You will see the importance of this command shortly.

Step 8: Exit kills off the command prompt.

I very rarely use a command prompt; my preference is to run a batch file containing the above commands. All I need to do is double click on that batch file and let Windows do the donkeywork.

Top

Batch file processing

Using a text editor create a new text file and type this line into it:

perl.exe test.pl

Save it to folder c:\a_perl with the following name run.bat Run this batch file from Explorer by double clicking on it.

I hope you were impressed by the result, batch file ran, followed by Perl running your script and finally batch file ending. I admit a little fast you probably only saw the command window for a short time. Now add the pause command to your batch file and run it again.

perl.exe test.pl
pause

Check Bat

That one batch file will allow you to run any of your scripts however before you get carried always make sure your scripts compile first before running them. For this I use a second batch named check.bat and add switches to the perl.exe the two I highlighted above. Create a new text file and add the following lines:

perl.exe -c -W test.pl
pause

When run, this batch file performs a syntax check (-c) with all warnings (-W) on it does not execute the Perl script.

Before running the above batch file, create an error in the test file. For example edit test.pl copy and paste the print line several times, on any line remove a quote save the file. Now run check.bat

Correct the error and run it again. With all the errors removed you can use run.bat to see what your script produces.

Top

Summary

Using only two very basic batch files you can run Perl independent of Uniform Server and Windows it makes an excellent portable development tool for Perl programs.

  File name: run.bat  
perl.exe test.pl

pause

 

  File name: check.bat  
perl.exe -c -W test.pl

pause

Top

Relative paths

I mentioned you must use full paths to the perl.exe file that’s not strictly true! You can use relative paths, so long as they lead Windows to the executable.

Create a new folder in c:/a_perl named down now move the two bat files (run and check) into it.

When you run these batch files Windows will be unable to find either the perl.exe or your test.pl script.

To the rescue the two dots and a back slash, these move up the folder tree one level. Add these to the paths in your two batch files they will look like this:

  File name: run.bat  
..\perl.exe ..\test.pl

pause

 

  File name: check.bat  
..\perl.exe -c -W ..\test.pl

pause

One extremely important point Perl uses as a reference point the location (path) of the program that called it. It does not use the path that it resides in.

When Perl uses relative paths in calculations these are referenced to the location of the calling program in our case the batch files.

Top

Complete example

Expanding the above introduction I am now going provide a more practical example this uses some of the system commands and introduces user input and output.

Set-up

Create a folder anywhere you like choose a suitable name I will be using perl_examples.

Copy the two files perl.exe and perl58.dll located in Uniform Server’s folder *\Uniform Server\udrive\usr\bin to perl_examples.

Create four blank text files named test.pl, go.bat, check.bat and run.bat add the text shown below to each file:

File Name Text Comment
test.pl   Your test script, you can choose any name you like, must have the extension .pl if you change the name change batch files to match.
check.bat perl.exe -c -W test.pl
pause
Run this first to check your script (test.pl) for syntax errors. It does not run your script only checks for errors. To give you a chance to view any results pause is included to halt execution of the bat file until a key is pressed.
run.bat perl.exe test.pl
pause
This runs your script (test.pl) again pause is included to give you a chance to view any output from your script.
go.bat perl.exe test.pl Runs your Perl script (test.pl) and closes. Assumes you are not outputting text to the command prompt. If you do include a pause command in your script or use run.bat.

Note: The above file names are insignificant you can use whatever you like however do not change the file extension.

Hello World Script

Add the following lines to test.pl

<?
print "Hello World\n";
print "Hello World\n";
print "Hello World\n";
?>

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\perl_examples>perl.exe -c -W test.pl

test.pl syntax OK

C:\perl_examples>pause Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat C:\perl_examples>perl.exe test.pl

Hello World
Hello World
Hello World

C:\perl_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Perl script is run and displays the out from the print commands

Waits for user input

go.bat Screen flashes No pause in the script.

Top

Streams

Data is pushed around a PC and across the Internet in a serial format consisting of a stream of ones and zeros. Data from a keyboard and data to a screen are referred to as the standard input and standard output streams. The source and destining of these streams can be changed, what is interesting, data can be treated as file input and output. These streams are automatically available to Perl CLI and identified with the constants STDIN and STDOUT respectively.

User Input

Open test.pl delete its content and add the following lines:

system('cls');
print "Enter some text\n";
$input = <STDIN>;
chomp $input;
print "The text you entered was $input \n";
system('pause');

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\perl_examples>perl.exe -c -W test.pl

test.pl syntax OK

C:\perl_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat Enter some text

Test 1234
The text you entered was Test 1234
Press any key to continue . . .

C:\perl_examples>pause
Press any key to continue . . .

Screen cleared using: system('cls');

Enter request: print "Enter some text\n";
Get user input: $input = <STDIN>;
Clean input: chomp $input;
Print result: print "The text you entered was $input \n";
Pause: system('pause');
Pause from: Batch file

go.bat Enter some text

Test 1234
The text you entered was Test 1234
Press any key to continue . .

Screen cleared using: system('cls');

Enter request: print "Enter some text\n";
Get user input: $input = <STDIN>;
Clean input: chomp $input;
Print result: print "The text you entered was $input \n";
Pause: system('pause');

Top

Reading a text file

Create a new text file named data.txt and add the following lines

First Line
Second Line
Third Line

Open test.pl delete its content and add the following lines:

system('cls');

$file ="data.txt";
open(INFILE,$file);
@some_txt=<INFILE>;
close(INFILE);

foreach $text(@some_txt){
print $text;
}

system('pause');

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\perl_examples>perl.exe -c -W test.pl

test.pl syntax OK

C:\perl_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat First Line

Second Line
Third Line
Press any key to continue . . .

C:\perl_examples>pause
Press any key to continue . . .

Screen cleared using: system('cls');

Set a variable to the file: $file ="data.txt";
Open the file for reading: open(INFILE,$file);
Read the file into array some_text: @some_txt=<INFILE>;
Close the file: close(INFILE);
Loop through the array: foreach $text(@some_txt){
Print each line to the screen: print $text;
Wait for user: system('pause');
Pause from: Batch file

go.bat First Line

Second Line
Third Line
Press any key to continue . . .

Same as above without Pause from: Batch file

Top

Write to a text file

Open test.pl delete its content and add the following lines:

system('cls');

$some_data[0]="New line one\n";
$some_data[1]="New line two\n";
$some_data[3]="New line three\n";

$file ="new_data.txt";

open(OUTFILE,">$file");
foreach $save(@some_data){
print OUTFILE $save;
}
close(OUTFILE);

print "File written\n";
system('pause');

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\perl_examples>perl.exe -c -W test.pl

test.pl syntax OK

C:\perl_examples>pause
Press any key to continue . . .

Batch file enters commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat File written

Press any key to continue . . .

C:\perl_examples>pause
Press any key to continue . . .

Screen cleared using: system('cls');

Build text array:
$some_data[0]="New line one\n";
$some_data[1]="New line two\n";
$some_data[3]="New line three\n";


Set a variable to the file: $file ="new_data.txt";
Open the file for output: open(OUTFILE,">$file");
Read the file into array some_text: @some_txt=<INFILE>;
Loop through the array: foreach $save(@some_data){
Print each line to the file: print OUTFILE $save;
Close the file: close(INFILE);
Wait for user: system('pause');
Pause from: Batch file

go.bat File written

Press any key to continue . . .

Same as above without Pause from: Batch file
new_data.txt New line one

New line two
New line three

Lines written to file.

Top

Summary

I have shown how easy it is to use Perl CLI. You can avoid a command prompt and all its associated typing by using three batch files. Uniform Server’s prime use of Perl is in CGI mode to server interactive pages.

Top

Quick Perl CGI


  Ric