About Me

Showing posts with label PERL. Show all posts
Showing posts with label PERL. Show all posts

Friday, 20 April 2012

PERL - MySQL Query

PERL - MySQL Query

Executing a query using the MySQL module is a two step process - very straight forward. We define a query in the form of a scalar variable then call upon that variable using our connection script and the query function.

perlmysqlquery.pl:

# DEFINE A MySQL QUERY
$myquery = "INSERT INTO $tablename 
(id, product, quantity) 
VALUES (DEFAULT,'pineapples','15')";

# EXECUTE THE QUERY FUNCTION
$execute = $connect->query($myquery);

PERL - MySQL Insert Query

Here we introduce the affectedrow() function along with the insertid() function. You can probably guess what the affected rows function does but insertid is unique. Inserid() returns the 'id' of the last inserted row, that is it will return an id if you have an id field set up to auto-increment in your MySQL table.

perlinsertquery.pl:

#!/usr/bin/perl

use Mysql;

print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# DEFINE A MySQL QUERY
$myquery = "INSERT INTO 
$tablename (id, product, quantity) 
VALUES (DEFAULT,'pineapples','15')";

# EXECUTE THE QUERY FUNCTION
$execute = $connect->query($myquery);

# AFFECTED ROWS
$affectedrows = $execute->affectedrows($myquery);

# ID OF LAST INSERT
$lastid = $execute->insertid($myquery);

print $affectedrows."<br />";
print $lastid."<br />";
These functions could be run without defining them as scalar variables as well.

PERL - MySQL SELECT Query

Queries that use the SELECT clause are a little more exciting. Here we introduce two new functions, the numrows() function and the numbfields() function. Both of these do exactly as they say, one fetches the number of rows returned with as the query executes while the other fetches the number of fields returned.

easyselectfunctions.pl:

#!/usr/bin/perl

use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM $tablename";

# EXECUTE THE QUERY
$execute = $connect->query($myquery);

$rownumber = $execute->numrows();
$fieldnumber = $execute->numfields();

# PRINT THE RESULTS
print $rownumber."<br />";
print $fieldnumber."<br />";
Two numbers should be printed to your web browser.

PERL - MySQL fetchrow()

The fetchrow() function does exactly as it says it does, it goes out and fetches a row that matches your MySQL Query. An array is returned and each element represents a column value for the fetched row. If the query is intended to return multiple rows, fetchrow() must be called again and again. This is easily accomplished with a while loop.

fetchrow.pl:

#!/usr/bin/perl

use Mysql;

print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM $tablename";

# EXECUTE THE QUERY FUNCTION
$execute = $connect->query($myquery);

# HTML TABLE
print "<table border='1'><tr>
<th>id</th>
<th>product</th>
<th>quantity</th></tr>";

# FETCHROW ARRAY

while (@results = $execute->fetchrow()) {
 print "<tr><td>"
 .$results[0]."</td><td>"
 .$results[1]."</td><td>"
 .$results[2]."</td></tr>";
}

print "</table>";

PERL - Select Database

PERL - Select Database

In order to perform even the simplest of queries we must first select a database to be working with. Since we have our database name already listed with our config variables, things will be quite simple.

perlmysqlselectdb.pl:

#!/usr/bin/perl

# PERL MODULE
use Mysql;

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);
Notice how the syntax requires that we connect to our host each time we perform a function. You will see this with nearly every script we execute. Once we are connected, the sky is the limit as to what queries we can execute.

PERL - List Tables Function

A function exists to list the tables in a database just like the listdbs() function. Use the listtables() function to list each table in a database.

listtables.pl:

#!/usr/bin/perl

use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# LISTTABLES()
@tables = $db->listtables;

# PRINT EACH TABLE NAME
@tables = $connect->listtables;
foreach $table (@tables) {
 print "$table<br />";
}
The database is defined when we run the $connect variable. To change the script to a different database simply run a new selectdb() function or change the $database variable.

PERL - MySQL Connect

PERL - MySQL Connect

The MySQL module works only with the MySQL platform. We can maintain the same variables from the previous example to connect to MySQL.

perlmysqlconnect.pl:

#!/usr/bin/perl

# PERL MODULE
use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT
$connect = Mysql->connect($host, $database, $user, $pw);
If this script was run on your web server through a web browser, you should be starring at a blank white screen and all is well.

PERL - MySQL listdbs()

Once PERL has established a connection we can execute any of the built in module functions. A great introductory function is the listdbs function. This function reads from the MySQL platform and places the name of each database into an array.

listdbs.pl:

@databases = $connect->listdbs;
We can then loop through this array and print out our results to the browser.

listdbs2.pl:

#!/usr/bin/perl

# PERL MODULES
use Mysql;

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# LISTDBS()
@databases = $connect->listdbs;
foreach $database (@databases) {
 print "$database<br />";
}

PERL - MySQL Module

PERL - MySQL Module

MySQL queries and the like can be executed with PERL via the MySQL Module. This module should already be installed with your web server if not contact your web host.

As a quick overview, this module installs the necessary functions required to execute MySQL queries using a PERL script. Please take note that this module only works with the MySQL platform. Other SQL platforms will require the use of the DBI module discussed in our PERL DBI Module lesson.

PERL - MySQL Config

Before we dive head first into the functions, we may want to set up some config variables that we will be calling upon in each script to first connect to our database. Have the following information easily accessible.
  • Our Web Host's data source name (DSN)
  • User Name for the MySQL Database
  • Password for the MySQL Database
  • Name of Database
  • Name of Table(s)

perlmysqlconfig.pl:

#!/usr/bin/perl

# PERL MODULE WE WILL BE USING
use Mysql;

# MySQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";
A config set-up like this simplifies our connection script and the queries that will be executed later.

PERL - DBI Query

PERL - DBI Query

Queries must be prepared and then executed. Two lines of code are required for this, first the prepare() function and then the execute() function.

PERL - DBI Prepare()

Inside the prepare() function lies the actual SQL query. Essentially the prepare function acts precisely like the console of an SQL platform. If you've been following along, all we need to do is define a variable with a(n) SQL statement. Then create a query handle and run our $connect statement along with the prepare function as outlined below.
The only main difference is that we have to use PERL's escaping characters and we probably have to use them more often.

dbipreparequery.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

# DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";

# PERL DBI CONNECT
$connect = DBI->connect($dsn, $user, $pw);

# PREPARE THE QUERY
$query = "INSERT INTO inventory (id, product, quantity) VALUES (DEFAULT, tomatoes, 4)";
$query_handle = $connect->prepare($query);

PERL - DBI Execute

Once the query has been prepared, we must execute the command with the execute function. This is accomplished in one final line appended to the code above.

dbiexecutequery.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

# DATA SOURCE NAME
$dsn = "dbi:$platform:$database:$host:$port";

# PERL DBI CONNECT
$connect = DBI->connect($dsn, $user, $pw);

# PREPARE THE QUERY
$query = "INSERT INTO inventory (id, product, quantity) VALUES (DEFAULT, 'tomatoes', '4')";
$query_handle = $connect->prepare($query);

# EXECUTE THE QUERY
$query_handle->execute();

PERL - DBI Select Queries

Select queries fetch results and then return those results in the form of an array. Accessing the results of the array requires first that we bind the columns to variable names. Then we just need to set up a loop to loop through each row and print back the results to our browser.

dbiselectquery.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

# DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";

# PERL DBI CONNECT
$connect = DBI->connect($dsn, $user, $pw);

# PREPARE THE QUERY
$query = "SELECT * FROM inventory ORDER BY id";
$query_handle = $connect->prepare($query);

# EXECUTE THE QUERY
$query_handle->execute();

# BIND TABLE COLUMNS TO VARIABLES
$query_handle->bind_columns(undef, \$id, \$product, \$quantity);

# LOOP THROUGH RESULTS
while($query_handle->fetch()) {
   print "$id, $product, $quantity <br />";
} 
Two new functions were introduced in that last example, the bind_columns and the fetch() functions. Both are fairly self explanatory. Variable names are assigned to our column values via the bind_column function and the fetch() function goes out and fetches the rows matching the query

PERL - Data Source Name (DSN)

PERL - Data Source Name (DSN)

In order to connect to our database platform we first need to know our web server's data source name. This information should be readily accessible in your server's documentation. There are four pieces that actively make up a DSN.
  • Name of SQL Platform (SQL Server, Oracle, DB2, MySQL, etc).
  • Database Name
  • Host Name (www.myhost.com)
  • Port Number
This information is available from your web host provider and can be defined in PERL as follows:

datasourcename.pl:

$dsn = "dbi:SQL Platform:database_name:host_name:port";
Since we plan on executing our scripts from our web server through our browser, we can alternatively substitute our host's name with the term localhost.

localhost.pl:

$dsn = "dbi:SQL_Platform:database_name:localhost:port";

PERL - DBI Connect

Previously, we had set up a config script with some information about our web host and SQL platform including a user name and password. We can now plug all those variables into the connection string and connect to our database.
We can establish a connection with a script like the following.

DBIconnect.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

#DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";


# PERL DBI CONNECT
$DBIconnect = DBI->connect($dsn, $user, $pw);

PERL - Database Handle

On a side note, we have also created what is known as a database handle. Our variable, $DBIconnect, is now the handle which we will have to use each time we wish to execute a query. We should probably go ahead and shorten up that handle since we will be using it in every query script.

databasehandle.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

#DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";

# PERL DBI CONNECT (RENAMED HANDLE)
$dbstore = DBI->connect($dsn, $user, $pw);
The handle has been changed from $DBIconnect, to a more descriptive name.

PERL - Connection Error(s)

An error string variable exists for this module. We can further modify our script with the die() function to terminate the script upon connection failure. The error message is usually printed in your web server's error log(s).

databasehandle.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# CONFIG VARIABLES
$platform = "mysql";
$database = "store";
$host = "localhost";
$port = "3306";
$tablename = "inventory";
$user = "username";
$pw = "password";

#DATA SOURCE NAME
$dsn = "dbi:mysql:$database:localhost:3306";

# PERL DBI CONNECT (RENAMED HANDLE)
$dbstore = DBI->connect($dsn, $user, $pw) or die "Unable to connect: $DBI::errstr\n";

PERL - DBI Module(s)

PERL - DBI Module(s)

PERL is capable of running SQL and MySQL queries including: inserts, selects, updates, deletes, etc through a module termed DBI. Often your web host will already have this module as well as DBD::mysql already installed. DBI stands for database interface. Any functions associated with DBI should work with all the available SQL platform including: SQL Server, Oracle, DB2, and MySQL.


Before continuing, be sure the following modules are installed:
  • DBI
  • DBD::mysql
Once they are installed, we can build the introduction to our script by telling PERL to use these modules as follows:

dbimodules.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;
Again, these modules allow for us to call upon functions specific to working with a any database platform including MySQL. These modules must be in "use" to ensure proper functionality of our scripts.

PERL - DBI Config

We will be calling on our database, table, and host machine from time to time. We recommend setting up a some variables for your database and table name, so that you can call upon them as you wish throughout this brief tutorial. You may also set up some variables for your user name and password as we will also be needing to connect to your MySQL web host.

dbiconfig.pl:

#!/usr/bin/perl

# PERL MODULES WE WILL BE USING
use DBI;
use DBD::mysql;

# DBI CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

PERL - Chomp

PERL - Chomp

Let's take another look at our agencolor.pl script. This script asked for two user inputs and returned an unformatted string and our variables as a result on the last line.

agencolor.pl:

#! usr/bin/perl
print "How old are you?";
$age = <>;
print "What is your favorite color?";
$color = <>;
print "You are $age, and your favorite color is $color.";
Here we have asked two questions, stored the user's input into two separate variables and printed out the results all in just a few lines of code. Be sure to take note of the formatting here. The user is required to strike the "enter" key resulting in a line break. We can remove the line break rather easily with the chomp() function. This function simply removes any erroneous line breaks and spacing from the end of our string.

agencolor2.pl:

#! usr/bin/perl
print "How old are you?";
chomp ($age = <>);
print "What is your favorite color?";
chomp ($color = <>);
print "You are $age, and your favorite color is $color.";

Age 'N' Color 2:

Screen Capture of Command Prompt
Chomp should be used whenever input is acquired from your users.

PERL -

PERL - <STDIN>

<STDIN> stands for standard input. It can be abbreviated by using simple <>. By declaring a scalar variable and setting it equal to <STDIN> we set the variable equal to whatever will be typed by our user at the command prompt. Observe:

whatismyage.pl:

#! usr/bin/perl
print "How old are you?";
$age = <>;
print "WOW! You are $age years old!";

How old are you?:

Screen Capture of Command Prompt
Don't worry about the display being a little off the mark, we will cover the formatting in the next lesson. For now let's practice retrieving some user input using PERL.
Let's take this example one step further and also request the favorite color of our user.

agencolor.pl:

#! usr/bin/perl
print "How old are you?";
$age = <>;
print "What is your favorite color?";
$color = <>;
print "You are $age, and your favorite color is $color.";

Age 'N' Color:

Screen Capture of Command Prompt
Once again, our formatting leave a little to be desired, but the variables are working as they should, and for now this is all we need to know.

PERL - Beginning Scripting

You now have the knowledge required to code some mathematical scripts like the following.

circle.pl:

#! usr/bin/perl
print "What is the radius of the circle?";
chomp ($r = <>);
$diameter = (2 * $r);
$area = (3.14 * ($r ** 2));
$cir = ($diameter * 3.14);
print "Radius: $r\n Diameter: $diameter\n Circumference: $cir\n Area: $area";

Circles!:

Screen Capture of Command Prompt

PERL - Programming

PERL - Programming

PERL was designed to be simple and direct. We outlined earlier that file manipulation and grep style functions are the bread and butter of PERL. Often times these types of tasks will require some form of user input. PERL can do exactly that (imagine that) and these next few pages of tutorial will walk you through the process step by step.

PERL - User Input

PERL is capable of quickly taking input from a user then manipulating it in some fashion and spitting out some sort of result. Whether the task at hand is complex file manipulation or just a simple conversion script, your script may require some sort of user-input. With PERL this input comes from the command prompt or MS-DOS on a windows machine.
In a minute we will be taking a look at how to retrieve some user input via the command prompt but first, you may need to install a PERL compiler for your machine.

ActivePERL - PERL for Windows

PERL comes pre-installed on many operating systems, like Linux for example. For those of us running a version of Windows however, we must download and install some sort of program that allows us to access PERL scripts from DOS. There are many PERL compilations available for your machine. A simple Google search yields several million results.
ActivePERL is the simplest of installers available and it is also free to download. Download the program, follow the onscreen installation guide, and you should have an active installation of PERL ready to go.
To test the installation, make sure the program has fully completed installation and then run through the following:
  1. Click on Start, go to Run.
  2. Enter Command or cmd into the display box.
  3. At the command prompt type perl -v.
You should get some documentation about Larry Wall 1987-200X, and that means you are officially done installing PERL and ready to start creating some PERL scripts.

PERL - Testing...Testing Script

Just to be sure everything is running correctly. Open up notepad or your preferred simple text editor and let's make a beginning script. We'll have our script print to the command prompt with the print function just as we would if we were printing text to our web browser.

testingtesting.pl:

#! usr/bin/perl
print "Hello PERL!";
Copy the two lines above and save them in a directory that you are capable of accessing through DOS. Locate that directory in your DOS prompt and simply type the name of your PERL script into the command prompt to execute your script.

testingtesting.pl:

C:\>testingtesting.pl

Hello PERL!:

Screen Capture of Command Prompt
Upon execution, the script should print the words "Hello PERL!" at the bottom of your command prompt.
You should now have some basic concept of how to manage and run PERL scripts from the command prompt of your machine. Next we will be taking a look at how to manipulate user input via the command prompt.

PERL - Deleting Files

PERL - Deleting Files

Use the unlink function to delete specific files from your web server. The best solution is often to set a variable name equal to the URL of the file you wish to delete.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
    print "File deleted successfully.";
} else {
    print "File was not deleted.";
}

deletefiles.pl:

File deleted successfully.

PERL - Removing Multiple Files at Once

Multiple files can be removed at once if we first create an array of files to be deleted and then loop through each one. There are several ways to go about this process.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header
@files = ("newtext.txt","moretext.txt","yetmoretext.txt");
foreach $file (@files) {
    unlink($file);
}

PERL - Copying Files

PERL - Copying Files

We can duplicate a file using the copy function. Copy takes two values the URL of the file to be copied and the URL of the new file. Since we want to duplicate the file in this example, we won't change the directory path but instead, just give the file a new name. If we used the same file name or the same URL, PERL will rewrite over the file if permissions allow.

We also must use a new module, the copy module of course.

PERL Code:

#!/usr/bin/perl
use File::Copy;

print "content-type: text/html \n\n"; #The header
$filetobecopied = "myhtml.html.";
$newfile = "myhtml.html.";
copy($filetobecopied, $newfile) or die "File cannot be copied.";
Here, we have simply duplicated the "myhtml.html" file and will be using it in further examples.
If we wanted to copy the file to a new directory, we can edit our variables to match the directory we wish to copy the file to.

PERL Code:

#!/usr/bin/perl
use File::Copy;

print "content-type: text/html \n\n"; #The header
$filetobecopied = "myhtml.html.";
$newfile = "html/myhtml.html.";
copy($filetobecopied, $newfile) or die "File cannot be copied.";
Now we have copied the file from its current directory to an HTML directory.
When using PERL on the web, it is best to use complete internet URL. We used a shorthand way in the example but a better solution may be to hardcode the full URL meaning; http://www.your.com/myhtml.html.

PERL - Moving Files

Moving a file requires the use of the move function. This functions works exactly as the copy function from above and we send PERL the same module. The difference is that instead of copying we are 'cutting' the file and sending it to a new location. It works the same as cutting and pasting text from an office document to another.

PERL Code:

#!/usr/bin/perl
use File::Copy;

print "content-type: text/html \n\n"; #The header
$oldlocation = "myhtml.html";
$newlocation = "html/myhtml.html";
move($oldlocation, $newlocation);
Now our file has been completly removed from its current location and placed into the new location.

PERL - Reading from a File

PERL - Reading from a File

It is possible to read lines from files and input them using the <> input operator. By placing the file handle inside of the input operator, your script will input that line of the file.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header
$HTML = "myhtml.html";
open (HTML) or die "Can't open the file!";
print <HTML>;
close (HTML);

myhtml.pl:

Here we have an HTML page with a paragraph.
Here we use a tiny PERL script to display several lines of HTML code. Each line is stored into an array and automatically printed to the browser in HTML format using the <> input operator.

PERL - Input Array

PERL is able to print out lines of other files with the use of arrays. Following the example above when we called our HTML file handle using the input operator, PERL automatically stored each iine of the file into a global array. It is then able to process each element of the array as we demonstrated in PERL Arrays. This makes it possible to integrate dynamic bits of HTML code with already existing HTML files.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header
$HTML = "myhtml.html";
open (HTML) or die "Can't open the file!";
@fileinput = <HTML>;
print $fileinput[0];
print $fileinput[1];
print $fileinput[2];
print $fileinput[3];
print "<table border='1' align='center'><tr>
<td>Dynamic</td><td>Table</td></tr>";
print "<tr><td>Temporarily Inserted</td>
<td>Using PERL!</td></tr></table>";
print $fileinput[4];
print $fileinput[5];
close (HTML);

dynamic.pl:

DynamicTable
Temporarily InsertedUsing PERL!
Here we have an HTML page with a paragraph.
To permanently change a file, replace the print function with the printf function.

PERL - File Creation

PERL - File Creation

Files are opened and created using the same sysopen function.


Our syntax open(FILEHANDLE, '$filename', permissions, CHMOD); or sysopen(FILEHANDLE, $filename, permissions, CHMOD);
With sysopen you may also set hexidecimal priviledges; CHMOD values. Sysopen also requires the declaration of a new module for PERL. We will be using the Fcntl module for now, more on this later. Below we have created a basic HTML (myhtml.html) file.

PERL Code:

#!/usr/bin/perl
use Fcntl; #The Module

print "content-type: text/html \n\n"; #The header
sysopen (HTML, 'myhtml.html', O_RDWR|O_EXCL|O_CREAT, 0755);
printf HTML "<html>\n"; 
printf HTML "<head>\n"; 
printf HTML "<title>My Home Page</title>"; 
printf HTML "</head>\n"; 
printf HTML "<body>\n"; 
printf HTML "<p align='center'>Here we have an HTML 
page with a paragraph.</p>";
printf HTML "</body>\n"; 
printf HTML "</html>\n"; 
close (HTML);

myhtml.html:

<html>
<head>
<title>My Home Page</title></head>
<body>
<p align='center'>Here we have an HTML page with a paragraph.</p>
</body>
</html>

myhtml.html-browser view:

Here we have an HTML page with a paragraph.
Our highlight shows the module we forced PERL to use, and the sysopen command. FH stands for filehandle, this value can be changed to whatever the author would like, it is just a way to reference the same file in a script. We then named the file with read and write priviledges, then told PERL to check if the file exists, and if not create a new file with 0755 CHMOD priviledges.
Below is the shorthand method, the difference here is our filehandle name has changed, and we are unable to set a CHMOD value with this function.

PERL Code:

open(TEXT,+<newtext.txt.);
printf TEXT "Check out our text file!";
close (TEXT);
We use the printf function instead of print to actually print our text into the file. Everything inside the printf function is embeded into our created file.

Perl - File Open

Perl - File Open

Files are opened using the open and sysopen function. Nothing fancy here at all. Either function may be passed up to 4 arguments, the first is always the file handle discussed earlier, then our file name also known as a URL or filepath, flags, and finally any permissions to be granted to this file.


When opening files as a programmer, there will generally be one of three goals in mind, file creation, appending files, or trunicating files.
Create:
Checks to see if the file exists, if not, perl creates a new file.
Append:
Sets the pointer to the end of the file, all output following will be added onto the tail end of the file.
Truncate:
Overwrites your existing file with a new one, this means all data in the old file will be lost.

PERL - Open a File

The following example will open a previously saved HTML document.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header

$FH = "filehandle";
$FilePath = "myhtml.html";

open(FH, $FilePath, permissions);
or
sysopen(FH, $FileName, permission);
Files with special characters or unusual names are best opened by first declaring the URL as a variable. This method removes any confusion that might occur as PERL tries to interpret the code. Tildas in filenames however require a brief character substitution step before they can be placed into your open statements.

PERL - File Permissions

File permissions are crucial to file security and function. For instance, in order to function, a PERL file (.pl) must have executable file permissions in order to function on your web server. Also, you may not want all of your HTML files to be set to allow others to write to them or over them. Here's a listing of what to pass to the open function when working with file handles.

Shorthand Flags:

EntitiesDefinition
< or rRead Only Access
> or wCreates, Writes, and Truncates
>> or aWrites, Appends, and Creates
+< or r+Reads and Writes
+> or w+Reads, Writes, Creates, and Truncates
+>> or a+Reads, Writes, Appends, and Creates

O_ Flags:

ValueDefinition
O_RDWRRead and Write
O_RDONLYRead Only
O_WRONLYWrite Only
O_CREATCreate the file
O_APPENDAppend the file
O_TRUNCTruncate the file
O_EXCLStops if file already exists
O_NONBLOCKNon-Blocking usability

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header
use Fcntl; #The Module

sysopen (HTML, '/home/html/myhtml.html', O_RDWR|O_EXCL|O_CREAT, 0755);
sysopen (HTML, >myhtml.html');

PERL - File Handling

PERL - File Handling

Now we shift gears as we introduce file handling. In PERL files are given a name, a handle, basically another way of saying alias. All input and output with files is achieved through filehandling. Filehandles are also a means by one program may communicate with another program.

PERL - Assigning Handles

A filehandle is nothing more than a nickname for the files you intend to use in your PERL scripts and programs. A handle is a temporary name assigned to a file. A great filehandle is an abreviated version of the filename. The example below illustrates how you will use a file handle in your PERL code.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header
$FilePath = "home/html/myhtml.html"
sysopen(HANDLE, $FilePath, O_RDWR);
printf HANDLE "Welcome to Tizag!";
close (HANDLE);

PERL - Files and the die Function

The die function exists in several programming languages. It is used to kill your scripts and helps pinpoint where/if your code is failing. We use this function as follows.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header

$filepath = "myhtml.html";

sysopen (HTML, '$filepath', O_RDWR|O_EXCL|O_CREAT, 0755) or die "$filepath cannot be opened.";
printf HTML "<html>\n"; 
printf HTML "<head>\n"; 
printf HTML "<title>My Home Page</title>"; 
printf HTML "</head>\n"; 
printf HTML "<body>\n"; 
printf HTML "<p align='center'>Here we have an HTML 
page with a paragraph.</p>";
printf HTML "</body>\n"; 
printf HTML "</html>\n"; 
close (HTML);
Now if for some reason PERL is unable to open or create our file, we will be told. It is good practice to use the die function and we will be using it more as we dive deeper into file handling.

PERL - Hashes

PERL - Hashes

Hashes are complex list data, like arrays except they link a key to a value. To define a hash, we use the percent (%) symbol before the name.

defineahash.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINE A HASH
%coins = ("Quarter", 25, "Dime", 10, "Nickel", 5);

# PRINT THE HASH
print %coins;

Display:

Nickel5Dime10Quarter25

PERL - Hash Indexing

Hashes can be indexed using two scalar variables. The variables $key and $value can be used to call on each key or value of the hash. We can use these variables to print out our hash again but this time let's make it a little more legible using a while loop.

legiblehash.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINE A HASH
%coins = ( "Quarter" , 25,
           "Dime" ,    10,
           "Nickel",    5 );
           
# LOOP THROUGH IT
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

legiblehash.pl:

Nickel, 5
Dime, 10
Quarter, 25
The each() function takes a hash. It then removes the topmost "Key and Value" pair. We store this into the variables $key and $value. Each time this loop iterates, the statement ($key, $value) = each(%thing) executes and the hash pops off the top key value pair and will continue doing so until it has gone through every pair in the hash. When it is done, each() returns false and the loop stops running.
Hashes work really well with HTML Tables.

tablehashes.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINE A HASH
%coins = ( "Quarter" , 25,
           "Dime" ,    10,
           "Nickel",    5 );

# SET UP THE TABLE
print "<table border='1'>";
print "<th>Keys</th><th>Values</th>";

# EXECUTE THE WHILE LOOP
while (($key, $value) = each(%coins)){
     print "<tr><td>".$key."</td>";
     print "<td>".$value."</td></tr>";
}
print "</table>";

tablehashes.pl:

KeysValues
Nickel5
Dime10
Quarter25
We have yet to sort our hash so you may experience different arrangements of your keys than shown in the display box.

PERL - Sorting Hashes by Key

Sorting any hash requires the use of the sort() function that has previously been outlined in PERL Arrays. We must also specify to PERL that we plan on sorting our hash by the key or value elements. The example below illustrates how to sort a hash and then print back the resulting hash.

sortkeys.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINE A HASH
%coins = ( "Quarter" , 25,
           "Dime" ,    10,
           "Nickel",    5 );
# FOREACH LOOP
foreach $key (sort keys %coins) {
     print "$key: $coins{$key}<br />";
}

sortkeys.pl:

Dime: 10
Nickel: 5
Quarter: 25
The $coins($key) represents the variable assigned by PERL to each value of each element. Use this short cut to quickly retrieve each value element from your hashes.

PERL - Sorting Hashes by Value

Hashes may be sorted by value. Often times this can be a very tricky process especially if we are dealing with numbers. With our current example, we have a "5" value for our nickel element. This will cause some problems as if we just sort the hash by value as it is, the nickel value is a "5" instead of "05".
We need to edit our hash to and change is the values to floating-point numbers. This way PERL will properly sort our hash by our values as the nickel element will be valued according to a value of "05" instead of "5".

sortvalues.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINE A HASH
%coins = ( "Quarter" , .25,
           "Dime" , .10,
           "Nickel", .05 );
# FOREACH LOOP
foreach $value (sort {$coins{$a} cmp $coins{$b} }
           keys %coins)
{
     print "$value $coins{$value}<br />";
}

sortvalues.pl:

Nickel 0.05
Dime 0.1
Quarter 0.25

PERL - Add an Element

Adding a new key/value pair can be done with one line of code. This example is straight forward, we add the key/value pairs of penny/01 and half dollar/50 to the existing hash.

addelements.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# BEGINNING HASH
%coins = ( "Quarter" , .25,
           "Dime" ,    .10,
           "Nickel",   .05 );
# PRINT THE OLD HASH
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

# ADD NEW ELEMENT PAIRS
$coins{Penny} = .01;
$coins{HalfDollar} = .50;

# PRINT THE NEW HASH
print "<br />";
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

addelements.pl:

Nickel, 0.05
Dime, 0.1
Quarter, 0.25

Nickel, 0.05
Dime, 0.1
HalfDollar, 0.5
Penny, 0.01
Quarter, 0.25
Once again, you may have different results in the display box since there was no sort function passed to our hash. The important part is that the two new key/value pairs were added increasing your hash from 3 to 5 entries.

PERL - Remove an Element

With the delete function we can remove an element from our hash in a similar fashion as demonstrated above.

removeelements.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# DEFINED HASH
%coins = ( "Quarter" , .25,
           "HalfDollar" ,    .50,
           "Penny" ,    .01,
           "Dime" ,    .10,
           "Nickel",   .05 );

# PRINT OLD HASH
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

# DELETE THE ELEMENT PAIRS
delete($coins{Penny});
delete($coins{HalfDollar});

# PRINT THE NEW HASH
print "<br />";
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

removeelements.pl:

Nickel, 0.05
Dime, 0.1
HalfDollar, 0.5
Penny, 0.01
Quarter, 0.25

Nickel, 0.05
Dime, 0.1
Quarter, 0.25
Here we reversed the process, eliminating our penny and half dollar keys from our hash altogether. It is not necessary to remove the value, PERL has taken care of this for us automatically.

PERL - While

PERL - While

While loops continually iterate as long as the conditional statement remains true. It is very easy to write a conditional statement that will run forever especially at the beginner level of coding. On a more positive note, while loops are probably the easiest to understand. The syntax is while (coditional statement) { execute code; }.

whilecounter.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET A VARIABLE
$count = 0;

# RUN A WHILE LOOP
while ($count <= 7) {
 # PRINT THE VARIABLE AND AN HTML LINE BREAK
 print "$count<br />";
 # INCREMENT THE VARIABLE EACH TIME
 $count ++;
}
print "Finished Counting!";

whilecounter.pl:

0
1
2
3
4
5
6
7
Finished Counting!

PERL - Next, Last, and Redo

Outlined below are several interrupts that can be used to redo or even skip iterations of code. These functions allow you to control the flow of your while loops.
Next
Place it inside your loop and it will stop the current iteration and go on to the next one.
Continue
Executed after each loop iteration and before the conditional statement is evaluated. A good place to increment counters.
Last
Last stops the looping immediately (like break)
Redo
Redo will execute the same iteration over again.

flowcontrol.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET A VARIABLE
$count = 0;
while ($count <= 7) {
  
 # SET A CONDITIONAL STATEMENT TO INTERRUPT @ 4
 if ($count == 4) {
  print "Skip Four!<br />";
  next;
 }
 # PRINT THE COUNTER
 print $count."<br />";

}
 continue {
  $count++;
 };
print "Loop Finished!";

flowcontrol.pl:

0
1
2
3
Skip Four!
5
6
7
Finished Counting!
Above, we skip the fourth iteration by incrementing the variable again. In the example we also print a line, "Skip Four!" just to make things easier to follow.

PERL - While Array Loop

Here we are just showing a method of looping through an array using a while loop. We use three variables to do this including: the array, a counter, and an index number so that each time the while loop iterates we also loop through each index of the array.

whilearrayloop.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET UP AN HTML TABLE
print "<table border='1'>";

# DEFINE AN ARRAY
@names = qw(Steve Bill Connor Bradley);

# COUNTER - COUNTS EACH ROW
$count = 1;

# COUNTS EACH ELEMENT OF THE ARRAY
$n = 0;

# USE THE SCALAR FORM OF ARRAY
while ($names[$n]) {
 print "<tr><td>$count</td><td>$names[$n]</td></tr>";
 $n++;
 $count++;
}
print "</table>";

while.pl:

1Steve
2Bill
3Connor
4Bradley

PERL - For Loops

PERL - For Loops

A for loop counts through a range of numbers, running a block of code each time it iterates through the loop. The syntax is for($start_num, Range, $increment) { code to execute }. A for loop needs 3 items placed inside of the conditional statement to be successful. First a starting point, then a range operator, and finally the incrementing value. Below is the example.

forloop.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";

# SET UP THE HTML TABLE
print "<table border='1'>";

# START THE LOOP, $i is the most common counter name for a loop!
for($i = 1; $i < 5; $i++) {
 # PRINT A NEW ROW EACH TIME THROUGH W/ INCREMENT
 print "<tr><td>$i</td><td>This is row $i</td></tr>";
}
# FINISH THE TABLE
print "</table>";

forloop.pl:

1This is row 1
2This is row 2
3This is row 3
4This is row 4
5This is row 5
We looped through one variable and incremented it. Using HTML, we were able to make a nice table to demonstrate our results.

PERL - Foreach Loops

Foreach is designed to work with arrays. Say you want to execute some code foreach element within an array. Here's how you might go about it.

foreachloop.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #The header

# SET UP THE HTML TABLE
print "<table border='1'>";

# CREATE AN ARRAY 
@names = qw(Steve Bill Connor Bradley);

# SET A COUNT VARIABLE
$count = 1;

# BEGIN THE LOOP
foreach $names(@names) {
 print "<tr><td>$count</td><td>$names</td></tr>";
 $count++;
}
print "</table>";

foreachloop.pl:

1Steve
2Bill
3Connor
4Bradley
We placed a table row counter for you to see each line more clearly. We use the variable $names to pull single elements from our array, PERL does the rest for us by looping through each element in our array. Use the sorting functions outlined in the PERL Arrays lesson.

PERL - If Statement Syntax

PERL - If Statement Syntax

If statements are conditional statements used to test whether or not some condition is met and then continue executing the script. The syntax for an if statement has a specific flow to it - if(conditional_statment) { code to execute; }.

PERL - If Conditional Statements

Conditional statements may involve logical operators and usually test equality or compare one value to another. Here's a look at some common conditional statements. Remember that the code to be executed will only execute if the condition in parentheses is met.

ifs.pl:

#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$x = 7;
$y = 7;

# TESTING...ONE, TWO...TESTING
if ($x == 7) {
 print '$x is equal to 7!';
 print "<br />";
}
if (($x == 7) || ($y == 7)) {
 print '$x or $y is equal to 7!';
 print "<br />";
}
if (($x == 7) && ($y == 7)) {
 print '$x and $y are equal to 7!';
 print "<br />";
}

if.pl:

$x is equal to 7!
$x or $y is equal to 7!
$x and $y are equal to 7!
These operators are discussed thoroughly in our PERL Operators lesson.

PERL - If Else

The else statement is a perfect compliment to an if statement. The idea behind them is that if the conditional statement is not met then do this. In hypothetical, plain english, "If this is true do this, if not do this."

ifelse.pl:

#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$name = "Sarah";
$x = 5;

# IF/ELSE STATEMENTS
if ($x > 10) {
 print "$x is greater than 10!";
} else {
 print "$x is not greater than 10!";
}
print "<br />";

# STRINGS ARE A LITTLE DIFFERENT
if ($name eq "Sarah") {
 print "Hello, $name!";
} else {
 print "You are not $name!";
}

PERL - Elsif Statements

Elsif statements test another conditional statement before executing code. This way multiple conditions can be tested before the script continues.

elsif.pl:

#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$x = 5;

# PLAY THE GUESSING GAME
if ($x == 6) {
 print "X must be 6.";
}
elsif ($x == 4) {
 print "X must be 4.";
}
elsif ($x == 5) {
 print "X must be 5!";
}
We could take this example a step further, adding an else statement at the bottom. This would serve as a catch all if none of the conditions were met.