PERL Tutorial PERL Introduction PERL - Before you begin

This tutorial will be covering the PERL syntax and should provide you with a very solid foundation of PERL for you to build upon. It is recommended that before you start walking through our tutorial that you have a general understanding of Web Development as well as some background knowledge of HTML and CSS as our tutorial is directed toward Web programming. We will be incorporating our PERL scripts with HTML, CSS, and PHP so if you are unfamiliar with any of these languages, it may be a good idea to touch base with the tutorials offered here, or elsewhere for that matter to familiarize yourself with the code we offer.

PERL - Practical Extraction and Report Language
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.

PERL - Getting Started
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.

PERL File Extension
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.

PERL - First Script
With PERL installed we are ready to dive into our first script. There are a few elements every PERL script must contain in order to function. Open up your favorite simple text editor, the file extension for PERL scripts is .pl. Save your files with this extension. The first line of every PERL script is a commented line directed toward the PERL interpreter. This line is generally the same from one instal of PERL to the next, it might look something like this:

firstscript.pl:
#!/usr/bin/perl

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.

PERL - HTTP Headers
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 print "content-type: text/html \n\n";

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.

PERL - Hello, PERL! Script
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 print "content-type: text/html \n\n"; print "Hello, PERL!";

You should see "Hello, PERL!" in the top left corner of your browser, pretty simple and straightforward.

PERL - Execute Your First Script
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.

PERL - Debugging Your Script(s)
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.

PERL - Case Sensitivity
File names, variables, and arrays are all case sensitive. If you capitalize a variable name when you define it, you must capitalize it to call it. A great tip for large scripts containing a vast number of variable names it is best to be consistent with your case sensitivity and maybe even develop a system for naming variables that makes sense to you. For the majority of us programmers, capitals are simply not an option.

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 print "Content-type: text/html \n\n"; # the header ######################################### #Comments start with a # #########################################

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.

PERL - Escaping Characters
In PERL we use the backslash (\) character to escape any type of character that might interfere with our code. For example there may become a time when you would like to print a dollar sign rather than use one to define a variable. To do this you must "escape" the character using a backslash (\).

escapecharacters.pl:
#!/usr/bin/perl print "Content-type: text/html \n\n"; #HTTP HEADER #CREATE STRINGS WITH ESCAPING CHARACTERS $string = "David paid \$4.34 for Larry\'s shirt."; $email = "youremail\@youremail.com"; #PRINT THE STRINGS print "$string<br />"; print "$email<br />";

print '$string and $email';

escapecharacters.pl:
David paid $4.34 for Larry's shirt. youremail@youremail.com $string and $email

PERL Variables

PERL - Define Some Variables
A variable is defined by the ($) symbol (scalar), the (@) symbol (arrays), or the (%) symbol (hashes). Here is what each type of variable should look like inside of a script.

definevariables.pl:
#!/usr/bin/perl print "Content-type: text/html \n\n"; #HTTP HEADER $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.

PERL - Scalar Variables
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 print "Content-type: text/html \n\n"; #HTTP HEADER # DEFINE SOME SCALAR VARIABLES $number = "5"; $exponent = "2 ** 8"; $string = "Hello, PERL!"; $stringpart_1 = "Hello, "; $stringpart_2 = "PERL!"; $linebreak = "<br />"; #HTML LINEBREAK TAG # PRINT THEM TO THE BROWSER print $number; print $linebreak; print $exponent; print $linebreak; print $string.$linebreak; print $stringpart_1.$stringpart_2;

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 print "Content-type: text/html \n\n"; #HTTP HEADER #DEFINE SOME ARRAYS @days = ("Monday", "Tuesday", "Wednesday"); @months = ("April", "May", "June"); #PRINT MY ARRAYS TO THE BROWSER print "@days"; print "<br />"; print "@months";

PERL - Define A Hash
Hashes are complex lists with both a key and a value part for each element of the list. We define a hash using the percent symbol (%).

definehashes.pl:
print "Content-type: text/html \n\n"; #HTTP HEADER #DEFINE SOME ARRAYS %coins = ("Quarter", 25, "Dime", 10, "Nickle", 5); %ages = ("Jerry", 45, "Tom", 22, "Vickie", 38); #PRINT MY HASHES TO THE BROWSER print "%coins"; print "<br />"; print "%ages";

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 print "content-type: text/html \n\n"; #HTTP HEADER # DEFINE SOME STRINGS $single = 'This string is single quoted'; $double = "This string is double quoted"; $userdefined = q^Carrot is now our quote^; # PRINT THEM TO THE BROWSER print $single."<br /gr44"; print $double."<br /gr44"; print $userdefined."<br /gr44";

PERL - Formatting Strings w/ Formatting Characters

Strings can be formatted to your liking using formatting characters. Some of these characters also work to format files created in PERL. Think of these characters as miniature functions. Character Description \L Transform all letters to lowercase \l Transform the next letter to lowercase \U Transform all letters to uppercase \u Transform the next letter to uppercase \n Begin on a new line \r Applys a carriage return \t Applys a tab to the string \f Applys a formfedd to the string \b Backspace \a Bell \e Escapes the next character \0nn Creates Octal formatted numbers \xnn Creates Hexideciamal formatted numbers \cX Control characters, x may be any character \Q Do not match the pattern \E Ends \U, \L, or \Q functions

formattingcharacters.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER # 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!"; # PRINT THE NEWLY FORMATTED STRINGS print $mystring."<br />"; print $newline."<;br />"; print $capital."<br />"; print $ALLCAPS";

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.

PERL - Substr() and String Indexing
The substr() function allows for the temporary replacement of characters in a string. We can change the string "Hello, PERL" to "Hello, World!" quite easily. Each character of the string is automatically assigned a numeric value by PERL, which means that we can index any of the characters in our strings with this number. PERL counts each character of the string beginning with 0 for the first character and continuing until it reaches the end of a string. Two arguments must be sent with our substr() function, the string you wish to index and the index number. If two arguments are sent, PERL assumes that you are replacing every character from that index number to the end.

stringreplace.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER # DEFINE A STRING TO REPLACE $mystring = "Hello, PERL!";

# PRINT THE BEGINNING STRING print $mystring."<br />"; # RUN OUR FUNCTION AND CHANGE OUR STRING substr($mystring, 7) = "World!"; # PRINT THE NEW STRING print $mystring;

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 print "content-type: text/html \n\n"; #HTTP HEADER # DEFINE A STRING TO REPLACE $mystring = "Hello, PERL!"; # PRINT THE BEGINNING STRING print $mystring."<br />"; # RUN OUR FUNCTION AND CHANGE OUR STRING substr($mystring, 7, 11) = "World"; # PRINT THE NEW STRING print $mystring;

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;

PERL - Mathematical Functions
With numbers comes math. Simple arithmetic operations are discussed in the PERL Operators lesson. Some mathematical functions require some additional PERL Modules. Here's a few trigonomic functions that will only function if your build of PERL has the Math::Trig module installed.

perltrig.pl:
#!/usr/bin/perl use Math::Trig; #USE THIS MODULE print "content-type: text/html \n\n"; #HTTP HEADER $real = 27; $float = 3.14159; $integer = -4; $exponent = 10e12; print tan($real); #TANGENT FUNCTION print "<br />"; print sin($float); #SINE FUNCTION print "<br />"; print acos($integer); #COSINE FUNCTION

perltrig.pl:

-3.27370380042812 2.65358979335273e-06 3.14159265358979-2.06343706889556i

PERL - Numbers with Operators
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 print "content-type: text/html \n\n"; #HTTP HEADER #PICK TWO NUMBERS $x = 14; $y = 10; #MULTIPLICATION OPERATOR $area = ($x * $y); print $area; print "<br />";

arithmeticoperations.pl:
140

PERL - Formatting Numbers
Computers are capable of calculating numbers that you and I probably never knew existed. This is especially true with calculations involving decimals, floating-point numbers, or percentages. You may find that one of the best solutions is to first convert your numbers when possible to real numbers (get rid of the decimal). You may then go ahead and perform the required operations such as multiplication, division, addition, or whatever and finally reintroduce the decimal using division.

peskydecimals.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER $hourlyrate = 7.50; #DECIMAL TO BE RID OF $hoursworked = 35; $no_decimal_rate = ($hourlyrate * 100); $netpay = ($no_decimal_rate * $hoursworked); $paycheck = ($netpay / 100); print print print print print "Hourly Wage: $hourlyrate<br />"; "Hours: $hoursworked<br />"; "No Decimal: $no_decimal_rate<br />"; "Net Pay: $netpay<br />"; "Pay Check: $paycheck<br />";

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).

• • •

Convert to real numbers. Perform the operation(s). Convert back to a decimal.

PERL Operators

PERL - Arithmetic Operators
Arithmetic operators are symbols used to execute general arithmetic procedures including: addition (+), subtraction (-), multiplication (*), and division (/).

Arithmetic Operators:
Operator + * / ** % Example 7+7 7-7 7*7 7/7 7 ** 7 7%7 Result = 14 =0 = 49 =1 = 823543 =0 Definition Addition Subtraction Multiplication Division Exponents Modulus

With these operators we can take a number and perform some simple math operations.

PERL Arithmetic:
#!/usr/bin/perl print "content-type: text/html \n\n"; #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 />"; #HTTP Header

Your browser should read:

arithmetic.pl:
81 81 81 81 81 81 plus 9 is 90 minus 9 is 72 times 10 is 810 divided by 9 is 9 to the 5th is 3486784401 modulus 79 is 2

PERL - Assignment Operators

Assignment operators perform an arithmetic operation and then assign the value to the existing variable. In this example, we set a variable ($x) equal to 5. Using assignment operators we will replace that value with a new number after performing some type of mathematical operation.

Assignment Operators:
Operator += -= *= /= %= **= Definition Addition Subtraction Multiplication Division Modulus Exponent Example ($x += 10) ($x -= 10) ($x *= 10) ($x /= 10) ($x %= 10) ($x **= 10)

PERL Assignment:
#!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER

#START WITH A NUMBER $x = 5; print '$x plus 10 is '.($x += 10); print "<br />x is now ".$x; #ADD 10 print '<br />$x minus 3 is '.($x -= 3); print "<br />x is now ".$x; #SUBTRACT 3 print '<br />$x times 10 is '.($x *= 10); print "<br />x is now ".$x. #MULTIPLY BY 10 print '<br />$x divided by 10 is '.($x /= 10); print "<br />x is now ".$x; #DIVIDE BY 10 print '<br />Modulus of $x mod 10 is '.($x %= 10); print "<br />x is now ".$x; #MODULUS print '<br />$x to the tenth power is '.($x **= 10); print "<br />x is now ".$x; #2 to the 10th

Each time an operation is performed our variable ($x) is permanently changed to a new value of $x.

PERL - Logical & Relational Operators
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 ==,eq !=,ne 5 == 5 5 eq 5 7 != 2 7 ne 2 Test: Is 5 equal to 5? Test: Is 7 not equal to 2? Result True True

<,lt >,gt <=,le >=,ge

7<4 7 lt 4 7>4 7 gt 4 7 <= 11 7 le 11 7 >= 11 7 ge 11

Test: Is 7 less than 4? Test: Is 7 greater than 4? Test: Is 7 less than or equal to 11?

False True True

Test: Is 7 greater than or equal to 11? False

Logical
Operator Defined &&,and ||,or Example Associates two variables using AND if (($x && $y) == 5)... 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 - Variables + Operators
Variables can be used with mathematical formulas using PERL Operators discussed in a previous lesson. Also, note that variables are case sensitive. "$myvariable," "$MYvariable," and "$Myvariable" can all be assigned different values due to case sensitivity. Numbers of course can be added, subtracted, or multiplied using operators. Strings as shown in the example below can also be used with operators.

PERL Code:
#!/usr/bin/perl print "Content-type: text/html \n\n"; #HTTP HEADER #TWO STRINGS TO BE ADDED $string1 = "Hello,"; $string2 = " World"; #ADD TWO STRINGS TOGETHER $string3 = "$myvariable + $Myvariable"; print $string3;

PERL Arrays

PERL - Array Variables
Arrays are complex variables that store list style data types. Each object of the list is termed an element and elements can either be a string, a number, or any type of scalar data including another variable. Place an array into a PERL script, using the at symbol (@).

perlarrays.pl:

#!/usr/bin/perl print "content-type: text/html \n\n"; # DEFINE AN ARRAY @coins = ("Quarter","Dime","Nickel"); # PRINT THE ARRAY print "@coins"; print "<br />"; print @coins; #HTTP HEADER

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.

PERL - Array Indexing
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 print "content-type: text/html \n\n"; # DEFINE AN ARRAY @coins = ("Quarter","Dime","Nickel"); # PRINT THE WHOLE ARRAY print "@coins"; # PRINT EACH SCALAR ELEMENT print "<br />"; print $coins[0]; #Prints the first element print "<br />"; print $coins[1]; #Prints the 2nd element print "<br />"; print $coins[2]; #Prints the 3rd element #HTTP HEADER

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 print "content-type: text/html \n\n"; # DEFINE AN ARRAY @coins = ("Quarter","Dime","Nickel"); # PRINT THE WHOLE ARRAY print "@coins"; # PRINT EACH SCALAR ELEMENT print "<br />"; print $coins[0]; #Prints the first element print "<br />"; print $coins[-1]; #Prints the last element print "<br />"; print $coins[-2]; #Prints 2nd to last element #HTTP HEADER

arrayindexing2.pl:
Quarter Dime Nickel Quarter Nickel Dime

PERL - The qw Subroutine
Quotations can be a hassle, especially if the array you wish to build has more than 5 elements. Use this neat little subroutine to remove the need for quotes around each element when you define an array.

PERL Code:
#!/usr/bin/perl print "content-type: text/html \n\n"; # DEFINE AN ARRAY WITHOUT QUOTES @coins = qw(Quarter Dime Nickel); print "@coins"; #HTTP HEADER

PERL - Sequential Number Arrays
PERL offers a shortcut for sequential numbers and letters. Rather than typing out each element when counting to 100 for example, we can do something like this:

sequentialarrays.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; # SHORTCUTS SAVE TIME @10 = (1 .. 10); @100 = (1 .. 100; @1000 = (100 .. 1000); @abc = (a .. z); # PRINT 'EM TO THE BROWSER print "@10<br />"; print "@100<br />"; print "@1000<br />"; print "@abc<br />"; #HTTP HEADER

PERL - Finding the length of an Array
Retrieving a numerical value that represents the length of an array is a two step process. First, you need to set the array to a scalar variable, then just print the new variable to the browser as shown below. There are two ways to set an array to scalar mode. We can use the scalar() function or we can redefine the array as a scalar variable.

findlength.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; @nums = (1 .. 20); @alpha = ("a" .. "z"); # SCALAR FUNCTION print scalar(@nums)."<br />"; print scalar(@alpha)."<br />"; # REDEFINE TO SCALAR #HTTP HEADER

$nums = @nums; $alpha = @alpha; print print print print "$nums<br />"; "$alpha<br />"; "There are $numofnums numerical elements<br />"; "There are ".scalar(@alpha)." letters in the alphabet!";

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.

PERL - Adding and Removing Elements
Adding elements is a breeze, we use the following functions to add/remove and elements:

• • • •

push() - adds an element to the end of an array. unshift() - adds an element to the beginning of an array. pop() - removes the last element of an array. shift() - removes the first element of an array.

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 print "content-type: text/html \n\n"; #HTTP HEADER # 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 />"; # BACK TO HOW IT WAS print "@coins";

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 push(@array, Element) pop(@array) shift(@array) delete $array[index] Definition Adds to the end of an array Removes the last element of the array Removes the first element of an array Removes an element by index number

unshift(@array, Element) Adds to the beginning of an array

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.($)

PERL - Slicing Array Elements
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 print "content-type: text/html \n\n"; #HTTP HEADER @coins = qw(Quarter Dime Nickel Penny); @slicecoins = @coins[0,2]; print "@slicecoins\n"; print "<br />";

When handling lists of sequential numbers, the range operator can quickly become your favorite tool for slicing up arrays.

myrangefriend.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER # 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

PERL - Replacing Array Elements
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."

PERL - Transform Strings to Arrays
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 print "content-type: text/html \n\n"; #HTTP HEADER # DEFINED STRINGS $astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $namelist = "Larry,David,Roger,Ken,Michael,Tom"; # STRINGS ARE NOW ARRAYS @array = split('-',$astring); @names = split(',',$namelist); # PRINT THE NEW ARRAYS print @array."<br />"; print "@names";

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 print "content-type: text/html \n\n"; #HTTP HEADER # A COUPLE OF ARRAYS @array = ("David","Larry","Roger","Ken","Michael","Tom"); @array2 = qw(Pizza Steak Chicken Burgers); # JOIN 'EM TOGETHER $firststring = join(", ",@array); $secondstring = join(" ",@array2); # PRINT THE STRINGS print "$astring<br />"; print "$string";

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 "content-type: text/html \n\n"; #HTTP HEADER @array2 = qw(Pizza Steak Chicken Burgers); $string = join("<br />",@array2); print "$string";

stringformatting.pl:
Pizza Steak Chicken Burgers

PERL - Sorting Arrays
The sort() function sorts each element of an array according to ASCII Numeric standards. Please view
ASCII-Table for a complete listing of every ASCII Numeric character.

Because the sort() relies on ASCII Numeric values, problems can arise with sorting capital letters and lower case letters. Let's walk through an example of exactly what can happen.

sortarrays.pl:
#!/usr/bin/perl print "content-type: text/html \n\n"; #HTTP HEADER # TWO ARRAYS @foods = qw(pizza steak chicken burgers); @Foods = qw(Pizza Steak chicken burgers); # SORT 'EM @foods = sort(@foods); @Foods = sort(@Foods); # PRINT THE NEW ARRAYS print "@foods<br />"; print "@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 print "content-type: text/html \n\n"; #HTTP HEADER @Foods = qw(Pizza Steak chicken burgers); # TRANSFORM TO LOWERCASE foreach $food (@Foods) { push(@foods "\L$food"); } # SORT @foods = sort(@foods); # PRINT THE NEW ARRAY print "@foods";

This example dives off the deep end, being that we introduced a foreach loop. Don't be afraid of the loop, just understand that concept that ideally, elements need to be converted before sorting using the sort() function.

PERL If 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 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 />"; # 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. PERL For

PERL - For Loops
A for loop counts through a range of numbers, reiterating lines of code each time the 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 for($start=1;$start<=5;$start++) { # PRINT A NEW ROW EACH TIME THROUGH W/ INCREMENT

print "<tr><td>$start</td><td>This is row $start</td></tr>"; } # FINISH THE TABLE print "</table>";

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.

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"; # 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>"; #The header

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 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 reiterations of code. These functions allow you to control the flow of your while loops. Next Next is a block of code that is executed after the loop is finished, but before the loop is evaluated for the next iteration Last Last stops the looping immediately (like break) Redo Redo will execute the same iteration over again. Continue Works with the next feature to interrupt the loop

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 if ($count == 4) { print "Skip Four!<br />"; $count ++; next; } # PRINT THE COUNTER AS USUAL print $count."<br />"; $count ++; } 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.

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 reiterates 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:
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); # PRINT THE HASH print %coins;

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 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 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:
Keys Dime Values 10 Quarter 25

Nickel

5

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:
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.

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 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

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 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 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 - 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:
Entities < or r Definition Read Only Access

> or w >> or a +< or r+ +> or w+ +>> or a+

Creates, Writes, and Truncates Writes, Appends, and Creates Reads and Writes Reads, Writes, Creates, and Truncates Reads, Writes, Appends, and Creates Definition Read and Write Read Only Write Only Create the file Append the file Truncate the file Stops if file already exists Non-Blocking usability

O_ Flags:
Value O_RDWR O_RDONLY O_WRONLY O_CREAT O_APPEND O_TRUNC O_EXCL O_NONBLOCK

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 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 Input

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:
Dynamic Table Temporarily Inserted Using PERL! Here we have an HTML page with a paragraph. To permanently change a file, replace the print function with the printf function.

PERL Copy

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 Delete

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"; $file = "newtext.txt"; if (unlink($file) == 0) { print "File deleted successfully."; } else { print "File was not deleted."; } #The header

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); }

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.

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 MSDOS 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. 2. 3. Click on Start, go to Run. Enter Command or cmd into the display box. 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!:

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!";

How old are you?:

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:

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.";

Age 'N' Color 2:

Chomp should be used whenever input is acquired from your users.

Databases

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 DBI Connect

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";

The variable $DBI::errstr contains the error information.

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 - 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 - 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 Select DB

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 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>";

Sign up to vote on this title
UsefulNot useful