Perl
Perl
PERL Introduction
Created in 1987 by Larry Wall, the UNIX based language has evolved into a powerful tool for the internet. It
was designed as a quick-fix patch program for UNIX based systems. The language is very simplistic, offering
optimum flexibility, perfect for short, straightforward scripting.
Since then its popularity has increased due to its flexibility, portability, usefulness, and its varied features. To
get started, load a simple text editor program and follow along in our examples.
First things first, you must have PERL 5.005 installed on your web hosting machine. Version 5.005 is
available for download via Perl.com, just follow the download links. They also offer installation help for a wide
variety of operating systems. We suggest you direct any installation help to the experts there.
This tutorial will be web based, working with and creating files over the internet. File management is the
bread and butter of the PERL language, and as you will discover, it's absolutely perfect for doing so.
A PERL script can be created inside of any normal simple-text editor program. There are several programs
available for every type of platform. There are many programs designed for programmers available for
download on the web.
Regardless of the program you choose to use, a PERL file must be saved with a .pl (.PL) file extension in
order to be recognized as a functioning PERL script. File names can contain numbers, symbols, and letters but
must not contain a space. Use an underscore (_) in places of spaces.
The comment points to the installation path of PERL, usually /usr/bin/perl. If not, you can locate the directory
tree to PERL somewhere in the documentation of your web server, or email your web host and they can specify
your PERL installation directory.
Because we are working in a web environment we are sort of jumping ahead of the game. We have to
introduce some HTTP headers so that PERL understands we are working with a web browser. To do this we
have to run another line of strange code called an HTTP header as you may have guessed. It looks something
like this:
firstscript.pl:
#!/usr/bin/perl
At this point our script still has no real functionality, all we have done thus far is locate our PERL interpreter
and tell it that we are going to be working with a web browser or in a web environment.
Now that we have located the interpreter and told PERL we are working with the web, we can print text to
the browser with the print function.
helloperl.pl:
#!/usr/bin/perl
You should see "Hello, PERL!" in the top left corner of your browser, pretty simple and straightforward.
Now it is time to upload your firstscript.pl to your web server and execute it. After you upload your file be
sure to CHMOD the script file and allow anonymous execution priviledge, generally a setting of 0755 works
perfectly.
You script is working perfectly if you are staring at a blank screen and didn't recieve a 500 or 404 error
message.
If you are using an FTP program to upload your scripts, set the upload type to ASCII or "Text". This setting
prevents the mysterious addition of random characters that sometimes happens when copying files across
different operating systems. Learning to do this prevents hours of headaches and frustration.
Another great debugging technique is to isolate the code you are currently working on. To do this you can
temporarily comment out lines of code to isolate only the section that is returning an error message.
PERL - Syntax
PERL follows a very specific syntax not unlike other programming languages. It is important to develop good
syntax habits as it will save you from having to debug things later, not to mention save yourself from eye strain
and mind numbing headaches.
casesensitivity.pl:
$VAriaBLE_NAmES = "string";
$LIKe_tHESE = "Another String";
$ARe_HArd_to_Type = "A Third String";
PERL - Comments
As with any programming language, PERL offers an escape from your code via the '#' sign. Any words,
spaces, or marks after a pound symbol will be ignored by the program interpreter, offering you the coder, a
chance to place reminders to yourself about your code. It's a great way to note specifics of your code to
yourself or others viewing your code/script. Comments are necessary for any script you wish to publish to
others or make readily available.
PERL Comment:
#!/usr/bin/perl
This comment is extreme and overdone, you might see more comments like this in scripts that are offered
free on the internet. Often programmers will include a large commented section as an installation or set-up
guide included right there in the script itself.
escapecharacters.pl:
#!/usr/bin/perl
escapecharacters.pl:
David paid $4.34 for Larry's shirt.
youremail@youremail.com
$string and $email
PERL Variables
definevariables.pl:
#!/usr/bin/perl
$myname = "some_value";
@array = ("value00","value01","value02");
%hash = ("Quarter", 25, "Dime", 10, "Nickle", 5);
-- OR --
my $myname = "some string";
my @array = ("value00", "value01", "value02");
my %hash =
The latter example using the my parameter is another means to define a variable that you might run across
as you gain more experience. It is not necessary to use the my parameter. Variables can be defined either way.
Scalar variables are simple variables containing only one element--a string or a number. Strings may
contain any symbol, letter, or number. Numbers may contain exponents, integers, or decimal values. The
bottom line here with scalar variables is that they contain only one single piece of data. What you see is what
you get with scalar variables.
definescalars.pl:
#!/usr/bin/perl
Scalars are very straight forward. Notice that we used a period (.) between each of our variables. This is a
special kind of operator that temporarily appends one string to another.
PERL - Array Variables
Arrays contain a list of scalar data (single elements). A list can hold an unlimited number of elements. In
PERL, arrays are defined with the at (@) symbol.
definearrays.pl:
#!/usr/bin/perl
definehashes.pl:
print "Content-type: text/html \n\n"; #HTTP HEADER
Hashes are very complex data types, for now just understand the syntax of how to define one. Later we will
take a closer look at these complex variables.
PERL - Strings
Strings are scalar as we mentioned previously. There is no limit to the size of the string, any amount of
characters, symbols, or words can make up your strings.
When defining a string you may use single or double quotations, you may also define them with the
q subfunction.
definestrings.pl:
#!/usr/bin/perl
formattingcharacters.pl:
#!/usr/bin/perl
# STRINGS TO BE FORMATTED
$mystring = "welcome to tizag.com!"; #String to be formatted
$newline = "welcome to \ntizag.com!";
$capital = "\uwelcome to tizag.com!";
$ALLCAPS = "\Uwelcome to tizag.com!";
Any combination of these special characters can be used at any time to properly punctuate your strings.
They also come in handy when printing out HTML with your PERL functions.
stringreplace.pl:
#!/usr/bin/perl
Because we only specified one numeric parameter for the string, PERL assumed we wanted to replace
every character after the 7th, with our new string. If we throw a third parameter in our function we can replace
only a chunk of our string with a new string.
stringreplace.pl:
#!/usr/bin/perl
We have essentially created the same script as in the previous example, the difference is that we replaced
ONLY the four letters of PERL with World, the exclamation point at the end was ignored.
PERL - Numbers
Numbers are scalar data. They exist in PERL as real numbers, float, integers, exponents, octal, and
hexidecimal numbers.
perlnumbers.pl:
$real = 27;
$float = 3.14159;
$integer = -4;
$exponent = 10e12;
perltrig.pl:
#!/usr/bin/perl
use Math::Trig; #USE THIS MODULE
perltrig.pl:
-3.27370380042812
2.65358979335273e-06
3.14159265358979-2.06343706889556i
Numbers aren't much without arithmetic operations. This next example is a sneak peak of the next lesson,
PERL Operators.
arithmeticoperations.pl:
#!/usr/bin/perl
arithmeticoperations.pl:
140
peskydecimals.pl:
#!/usr/bin/perl
peskydecimals.pl:
Hourly Wage: 7.5 Hours: 35
No Decimal: 750
Net Pay: 26250
Pay Check: 262.5
In this example we followed the steps stated above, first we removed the decimal from each number
involved in the calculation, ($hourlyrate and $hoursworked). Then we performed the operation ($netpay), and
finally introduced the decimal again by dividing our $netpay by the same number we used to get rid of the
decimal in the first place (100).
PERL Operators
Arithmetic operators are symbols used to execute general arithmetic procedures including: addition (+),
subtraction (-), multiplication (*), and division (/).
Arithmetic Operators:
Operator Example Result Definition
+ 7+7 = 14 Addition
- 7-7 =0 Subtraction
* 7*7 = 49 Multiplication
/ 7/7 =1 Division
** 7 ** 7 = 823543 Exponents
% 7%7 =0 Modulus
With these operators we can take a number and perform some simple math operations.
PERL Arithmetic:
#!/usr/bin/perl
#PICK A NUMBER
$x = 81;
$add = $x + 9;
$sub = $x - 9;
$mul = $x * 10;
$div = $x / 9;
$exp = $x ** 5;
$mod = $x % 79;
print "$x plus 9 is $add<br />";
print "$x minus 9 is $sub<br />";
print "$x times 10 is $mul<br />";
print "$x divided by 9 is $div<br />";
print "$x to the 5th is $exp<br />";
print "$x modulus 79 is $mod<br />";
arithmetic.pl:
81 plus 9 is 90
81 minus 9 is 72
81 times 10 is 810
81 divided by 9 is 9
81 to the 5th is 3486784401
81 modulus 79 is 2
Assignment Operators:
Operator Definition Example
+= Addition ($x += 10)
-= Subtraction ($x -= 10)
*= Multiplication ($x *= 10)
/= Division ($x /= 10)
%= Modulus ($x %= 10)
**= Exponent ($x **= 10)
PERL Assignment:
#!/usr/bin/perl
Each time an operation is performed our variable ($x) is permanently changed to a new value of $x.
Relationship operators compare one variable to another. (5 < 12) They are used to compare equality or
inequality of two or more variables, be it a string or numeric data.
Logical operators state and/or relationships. Meaning, you can take two variables and test an either or
conditional. Logical operators are used later on in conditionals and loops. For now, just be able to recognize
them in the upcoming examples.
Logical/Relational Operators:
Relational
Operator Example Defined Result
5 == 5
==,eq Test: Is 5 equal to 5? True
5 eq 5
7 != 2
!=,ne Test: Is 7 not equal to 2? True
7 ne 2
7<4
<,lt Test: Is 7 less than 4? False
7 lt 4
7>4
>,gt Test: Is 7 greater than 4? True
7 gt 4
7 <= 11
<=,le Test: Is 7 less than or equal to 11? True
7 le 11
7 >= 11
>=,ge Test: Is 7 greater than or equal to 11? False
7 ge 11
Logical
Operator Defined Example
&&,and Associates two variables using AND if (($x && $y) == 5)...
||,or Associates two variables using OR if (($x || $y) == 5)...
Please note that you must use each different operator depending of whether or not you are comparing
strings or numbers. In the table above, the black operators are for numbers and the red ones are for strings.
PERL Code:
#!/usr/bin/perl
print $string3;
PERL Arrays
perlarrays.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");
Check the syntax here. We printed the same array twice using quotes around the first line. Notice how the
line with quotes around it prints nicely to the browser leaving spaces between each word. PERL does this
automatically as it assumes the quotations are meant for a string and strings are usually comprised of words
that require spacing between each word.
Each element of the array can be indexed using a scalar version of the same array. When an array is
defined, PERL automatically numbers each element in the array beginning with zero. This phenomenon is
termed array indexing.
arrayindexing.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");
arrayindexing.pl:
Quarter Dime Nickel
Quarter
Dime
Nickel
Elements can also be indexed backwards using negative integers instead of positive numbers.
arrayindexing2.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");
PERL Code:
#!/usr/bin/perl
sequentialarrays.pl:
#!/usr/bin/perl
findlength.pl:
#!/usr/bin/perl
@nums = (1 .. 20);
@alpha = ("a" .. "z");
# SCALAR FUNCTION
print scalar(@nums)."<br />";
print scalar(@alpha)."<br />";
# REDEFINE TO SCALAR
$nums = @nums;
$alpha = @alpha;
findlength.pl:
20
26
20
26
There are 20 numerical elements
There are 26 letters in the alphabet!
Setting our array to a scalar data type transformed our array into scalar data. As a result PERL is forced to
count through each element and return a value representing the array.
Adding elements is a breeze, we use the following functions to add/remove and elements:
When adding elements using push() or shift() you must specify two arguments, first the array name and
second the name of the element to add. Removing an element with pop() or shift() only requires that you send
the array as an argument.
modifyarrays.pl:
#!/usr/bin/perl
# AN ARRAY
@coins = ("Quarter","Dime","Nickel");
# ADD ELEMENTS
push(@coins, "Penny");
print "@coins";
print "<br />";
unshift(@coins, "Dollar");
print "@coins";
# REMOVE ELEMENTS
pop(@coins);
print "<br />";
print "@coins";
shift(@coins);
print "<br />";
modifyarrays.pl:
Quarter Dime Nickel Our original Array, 3 elements.
Quarter Dime Nickel Penny Add penny to the end.
Dollar Quarter Dime Nickel Penny Add Dollar to the beginning.
Dollar Quarter Dime Nickel Remove Penny.
Quarter Dime Nickel Remove dollar, back to the original!
Array Functions:
Function Definition
push(@array, Element) Adds to the end of an array
pop(@array) Removes the last element of the array
unshift(@array, Element) Adds to the beginning of an array
shift(@array) Removes the first element of an array
delete $array[index] Removes an element by index number
It is also possible to remove any element by its indexed number. Just remember to use the scalar form of
the array when doing so.($)
There is no specific slice() function for slicing up elements of an array. Instead PERL allows us to create a
new array with elements of another array using array indexing.
slicendice.pl:
#!/usr/bin/perl
When handling lists of sequential numbers, the range operator can quickly become your favorite tool for
slicing up arrays.
myrangefriend.pl:
#!/usr/bin/perl
# SEQUENTIAL ARRAY
@nums = (1..200);
@slicenums = @nums[10..20,50..60,190..200];
print "@slicenums";
myrangefriend.pl:
11 12 13 14 15 16 17 18 19 20 21 51 52 53 54 55 56 57
58 59 60 61 191 192 193 194 195 196 197 198 199 200
Replacing elements is possible with the splice() function. Splice() requires a handful of arguments and the
formula reads: splice(@array,first-element,sequential_length,name of new elements).
Essentially, you send PERL an array to splice, then direct it to the starting element, count through how many
elements to replace, and then fill in the missing elements with new information.
replacewithsplice.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #HTTP Header
@nums = (1..20);
splice(@nums, 5,5,21..25);
print "@nums";
Take note of the fact that the actual replacement begins after the 5th element, starting with the number 6 in
the example above. Five elements are then replaced from 6-10 with the numbers 21-25. Let the "Ooohing" and
"Ahhhing" begin."
With the split function, it is possible to transform a string into an array. To do this simply define an array and
set it equal to a split function. The split function requires two arguments, first the character of which to split and
also the string variable.
stringtoarray.pl:
#!/usr/bin/perl
# DEFINED STRINGS
$astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$namelist = "Larry,David,Roger,Ken,Michael,Tom";
split.pl:
Rain Drops On Roses And Whiskers On Kittens
Larry David Roger Ken Michael Tom
Notice you have to send the split function where the split will occur. In the first example, the split was called
at each hyphen. In the latter example the names were split by a comma, allowing for the split to take place
between each name.
Likewise, we can use the join() function to rejoin the array elements and form one long, scalar string.
arraytostring.pl:
#!/usr/bin/perl
# A COUPLE OF ARRAYS
@array = ("David","Larry","Roger","Ken","Michael","Tom");
@array2 = qw(Pizza Steak Chicken Burgers);
join.pl:
David,Larry,Roger,Ken,Michael,Tom
Pizza Steak Chicken Burgers
The characters specified in our join() argument are the characters used in between each element of the
array. This allows us to format the new strings with blank spaces between each word. We could replace the
blank spaces with any characters including HTML Elements such as a line break tag.
stringformatting.pl:
#!/usr/bin/perl
print "$string";
stringformatting.pl:
Pizza
Steak
Chicken
Burgers
sortarrays.pl:
#!/usr/bin/perl
# TWO ARRAYS
@foods = qw(pizza steak chicken burgers);
@Foods = qw(Pizza Steak chicken burgers);
# SORT 'EM
@foods = sort(@foods);
@Foods = sort(@Foods);
So what happened? We performed the same function on two nearly identical arrays and achieved complete
different results. Capital letters have a lower ASCII Numeric value than lowercase letters. The fact that our
second array has a mix of capitals and lowercase throws our sorting out of whack. Perhaps the best option is to
first transform every element of the array into lowercase letters and then perform the sort function.
sortarrays.pl:
#!/usr/bin/perl
# TRANSFORM TO LOWERCASE
foreach $food (@Foods) {
push(@foods "\L$food");
}
# SORT
@foods = sort(@foods);
PERL If
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; }.
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 is equal to 7!';
print "<br />";
}
if.pl:
$x is equal to 7!
$x or $y is equal to 7!
$x and $y is 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 />";
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;
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.
PERL For
forloop.pl:
#!/usr/bin/perl
forloop.pl:
1 This is row 1
2 This is row 2
3 This is row 3
4 This is row 4
5 This 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.
foreachloop.pl:
#!/usr/bin/perl
# CREATE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
foreachloop.pl:
1 Steve
2 Bill
3 Connor
4 Bradley
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 - While
While loops continually reiterate 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
# SET A VARIABLE
$count = 0;
whilecounter.pl:
0
1
2
3
4
5
6
7
Finished Counting!
flowcontrol.pl:
#!/usr/bin/perl
# SET A VARIABLE
$count = 0;
while ($count <= 7) {
}
continue {
print $count."<br />";
$count++;
};
print "Loop Finished!";
flowcontrol.pl:
0
1
2
3
Skip Four!
5
6
7
Finished Counting!
Above, we skip the fourth reiteration by incrementing the variable again. In the example we also print a line,
"Skip Four!" just to make things easier to follow.
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 reiterates we
also loop through each index of the array.
whilearrayloop.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
while.pl:
1 Steve
2 Bill
3 Connor
4 Bradley
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);
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
# 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 separates each element of the hash and by throwing the variables in the while loop as
we did, each time the code reiterates itself, those variables are redefined to each new key and value pair. This
is a chunk of code that doesn't make a whole lot of sense, just memorize it or keep it handy to copy and paste.
Hashes work really well with HTML Tables.
tablehashes.pl:
#!/usr/bin/perl
# DEFINE A HASH
%coins = ( "Quarter" , 25,
"Dime" , 10,
"Nickel", 5 );
tablehashes.pl:
Keys Values
Quarter 25
Dime 10
Nickel 5
We have yet to sort our hash so you may experience different arrangements of your keys than shown in the
display box.
sortkeys.pl:
#!/usr/bin/perl
# 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.
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
# 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
# BEGINNING HASH
%coins = ( "Quarter" , .25,
"Dime" , .10,
"Nickel", .05 );
# PRINT THE OLD HASH
while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
}
addelements.pl:
Dime, 0.1
Nickel, 0.05
Quarter, 0.25
HalfDollar, 0.5
Dime, 0.1
Penny, 0.01
Nickel, 0.05
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.
With the delete function we can remove an element from our hash in a similar fashion as demonstrated
above.
removeelements.pl:
#!/usr/bin/perl
# DEFINED HASH
%coins = ( "Quarter" , .25,
"HalfDollar" , .50,
"Penny" , .01,
"Dime" , .10,
"Nickel", .05 );
removeelements.pl:
Nickel, 0.05
Penny, 0.01
HalfDollar, 0.5
Dime, 0.1
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 Management
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.
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
The die function exists in several programming languagas. 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
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 Code:
#!/usr/bin/perl
$FH = "filehandle";
$FilePath = "myhtml.html";
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.
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:
Entities Definition
< or r Read Only Access
> or w Creates, Writes, and Truncates
>> or a Writes, Appends, and Creates
+< or r+ Reads and Writes
+> or w+ Reads, Writes, Creates, and Truncates
+>> or a+ Reads, Writes, Appends, and Creates
O_ Flags:
Value Definition
O_RDWR Read and Write
O_RDONLY Read Only
O_WRONLY Write Only
O_CREAT Create the file
O_APPEND Append the file
O_TRUNC Truncate the file
O_EXCL Stops if file already exists
O_NONBLOCK Non-Blocking usability
PERL Code:
#!/usr/bin/perl
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 Input
PERL Code:
#!/usr/bin/perl
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 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
dynamic.pl:
Dynamic Table
Temporarily Inserted Using PERL!
PERL Copy
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;
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;
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 Code:
#!/usr/bin/perl
use File::Copy;
Now our file has been completly removed from its current location and placed into the new location.
PERL Delete
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
deletefiles.pl:
File deleted successfully.
PERL Code:
#!/usr/bin/perl
Command Prompt
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.
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.
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!:
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 UserInput
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!";
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.";
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!:
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.";
• 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
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.
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
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";
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
# 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";
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
# 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";
The handle has been changed from $DBIconnect, to a more descriptive name.
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
# 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";
dbipreparequery.pl:
#!/usr/bin/perl
# 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";
dbiexecutequery.pl:
#!/usr/bin/perl
# 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";
# 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";
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
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.
A config set-up like this simplifies our connection script and the queries that will be executed later.
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";
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.
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;
# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);
# LISTDBS()
@databases = $connect->listdbs;
foreach $database (@databases) {
print "$database<br />";
}
PERL-MySql Select DB
perlmysqlselectdb.pl:
#!/usr/bin/perl
# PERL MODULE
use Mysql;
# 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.
listtables.pl:
#!/usr/bin/perl
use Mysql;
# HTTP HEADER
print "Content-type: text/html \n\n";
# SELECT DB
$connect->selectdb($database);
# LISTTABLES()
@tables = $db->listtables;
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.
perlmysqlquery.pl:
# DEFINE A MySQL QUERY
$myquery = "INSERT INTO $tablename
(id, product, quantity)
VALUES (DEFAULT,'pineapples','15')";
perlinsertquery.pl:
#!/usr/bin/perl
use Mysql;
# SELECT DB
$connect->selectdb($database);
# AFFECTED ROWS
$affectedrows = $execute->affectedrows($myquery);
# ID OF LAST INSERT
$lastid = $execute->insertid($myquery);
easyselectfunctions.pl:
#!/usr/bin/perl
use Mysql;
# HTTP HEADER
print "Content-type: text/html \n\n";
# SELECT DB
$connect->selectdb($database);
$rownumber = $execute->numrows();
$fieldnumber = $execute->numfields();
fetchrow.pl:
#!/usr/bin/perl
use Mysql;
# SELECT DB
$connect->selectdb($database);
# DEFINE A MySQL QUERY
$myquery = "SELECT * FROM $tablename";
# HTML TABLE
print "<table border='1'><tr>
<th>id</th>
<th>product</th>
<th>quantity</th></tr>";
# FETCHROW ARRAY
print "</table>";