Perl Introducation..........
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 go over to perl.org and download the latest version of Perl (currently 5.10) or check that your web host has it installed. We suggest you direct any installation questions or perl problems to the Perl Forum (might want to bookmark this).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 if you were running it on linux:
firstscript-linux.pl:
#!/usr/bin/perl
And on a windows operating system it may resemble:firstscript-windows.pl:
#!D:\Perl\bin\perl
In this tutorial we will assume you are running on a linux
server (the most common web server), but if you are on windows make sure you
use the correct path! The comment points to the installation path of Perl,
usually /usr/bin/perl. 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!";
Display:
Perl - Execute Your First Script
Now it is time to upload your firstscript-linux.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.Your 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:
youremail@youremail.com
$string and $email
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
$somenumber = 4;
$myname = "some string";
@array = ("value00","value01","value02");
%hash = ("Quarter", 25, "Dime", 10, "Nickle", 5);
## OR ##
my $somenumber = 4;
my $myname = "some string";
my @array = ("value00", "value01", "value02");
my %hash = ("Quarter", 25, "Dime", 10, "Nickle", 5);
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, a number, or a reference. 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;
Display:
2 ** 8
Hello, Perl!
Hello, Perl!
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;
Display:
AprilMayJune
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 HASHES
%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;
Display:
Jerry45Vickie38Tom22
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 />";
print $double."<br />";
print $userdefined."<br />";
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 MYSITE.com!"; #String to be formatted
$newline = "welcome to \nMYSITE.com!";
$capital = "\uwelcome to MYSITE.com!";
$ALLCAPS = "\Uwelcome to MYSITE.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 is a rather complicated function. It can be used to do many things and we'll start with the most basic, grabbing a substring and move onto more advanced ideas further on.To use substr() to grab a substring, you need to give it both a string variable to pick something out of and an offset (which starts at 0). A string can be thought of as an array of characters, starting with element 0 at the beginning and +1 for each additional character. The string "hey" has 3 characters. The 0th element is "h", the 1st element is "e" and the 2nd and last element is "y".
The first argument of substr() is the string we want to take something from and the second argument is the offset, or where we want to start at.
stringreplace.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #HTTP HEADER
# DEFINE A STRING TO REPLACE
$mystring = "Hello, am I about to be manipulated?!";
# PRINT THE ORIGINAL STRING
print "Original String: $mystring<br />";
# STORE A SUB STRING OF $mystring, OFFSET OF 7
$substringoffset = substr($mystring, 7);
print "Offset of 7: $substringoffset<br />";
Display:
Offset of 7: am I about to be manipulated?!
Below we have gone on to the more advanced options of substr(), taking advantage of the last two arguments of the function: length and replace value. Rather than grabbing the whole string from the offset, we can just grab a chunk of it by specifying the length we want this substring to be.
The final argument, replace value, replaces the substring specified by the first three arguments with whatever we want. Let's change the original string to say something different by grabbing a part of the string and replacing it with "I want".
stringreplace.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #HTTP HEADER
# DEFINE A STRING TO REPLACE
$mystring = "Hello, am I about to be manipulated?!";
# PRINT THE ORIGINAL STRING
print "Original String: $mystring<br />";
# STORE A SUB STRING OF $mystring, OFFSET OF 7 AND LENGTH 10
$suboffsetANDlength = substr($mystring, 7, 10);
print "Offset of 7 and length of 10: $suboffsetANDlength<br />";
# CHANGE $mystring, OFFSET OF 7 AND LENGTH 10 AND
# REPLACE SUB STR WITH "I want"
$suboffsetANDlength = substr($mystring, 7, 10, "I want");
print "mystring is now: $mystring<br />";
Display:
Offset of 7 and length of 10: am I about
mystring is now: Hello, I want to be manipulated?!
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:
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:
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 integers (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 "Hourly Wage: $hourlyrate<br />";
print "Hours: $hoursworked<br />";
print "No Decimal: $no_decimal_rate<br />";
print "Net Pay: $netpay<br />";
print "Pay Check: $paycheck<br />";
peskydecimals.pl:
No Decimal: 750
Net Pay: 26250
Pay Check: 262.5
- Convert to real numbers.
- Perform the operation(s).
- Convert back to a decimal.
PERL - Arithmetic 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
|
PERL Arithmetic:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #HTTP Header
#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 />";
Your browser should read:arithmetic.pl:
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
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
|
Example
|
+=
|
Addition
|
($x += 10)
|
-=
|
Subtraction
|
($x -= 10)
|
*=
|
Multiplication
|
($x *= 10)
|
/=
|
Division
|
($x /= 10)
|
%=
|
Modulus
|
($x %= 10)
|
**=
|
Exponent
|
($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
Display:
x is now 15
$x minus 3 is 12
x is now 12
$x times 10 is 120
$x is now 120
$x divided by 10 is 12
x is now 12
Modulus of $x mod 10 is 2
x is now 2
$x to the tenth power is 1024
x is now 1024
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
|
Result
|
==,eq
|
5 == 5
5 eq 5 |
Test: Is 5 equal to 5?
|
True
|
!=,ne
|
7 != 2
7 ne 2 |
Test: Is 7 not equal to 2?
|
True
|
<,lt
|
7 < 4
7 lt 4 |
Test: Is 7 less than 4?
|
False
|
>,gt
|
7 > 4
7 gt 4 |
Test: Is 7 greater than 4?
|
True
|
<=,le
|
7 <= 11
7 le 11 |
Test: Is 7 less than or equal to 11?
|
True
|
>=,ge
|
7 >= 11
7 ge 11 |
Test: Is 7 greater than or equal to 11?
|
False
|
Logical
Operator
|
Defined
|
Example
|
&&,and
|
Associates two variables using AND
|
if (($x && $y) == 5)...
|
||,or
|
Associates two variables using OR
|
if (($x || $y) == 5)...
|
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
$myvariable = "Hello,";
$Myvariable = " World";
#ADD TWO STRINGS TOGETHER
$string3 = "$myvariable $Myvariable";
print $string3;
Display:
PERL - Array Variables
Arrays are a special type of variable 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"; #HTTP HEADER
# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");
# PRINT THE ARRAY
print "@coins";
print "<br />";
print @coins;
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"; #HTTP HEADER
# 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
arrayindexing.pl:
Quarter
Dime
Nickel
arrayindexing2.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #HTTP HEADER
# 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
arrayindexing2.pl:
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"; #HTTP HEADER
# DEFINE AN ARRAY WITHOUT QUOTES
@coins = qw(Quarter Dime Nickel);
print "@coins";
Display:
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"; #HTTP HEADER
# 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 />";
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"; #HTTP HEADER
@nums = (1 .. 20);
@alpha = ("a" .. "z");
# SCALAR FUNCTION
print scalar(@nums)."<br />";
print scalar(@alpha)."<br />";
# REDEFINE TO SCALAR
$nums = @nums;
$alpha = @alpha;
print "$nums<br />";
print "$alpha<br />";
print "There are $nums numerical elements<br />";
print "There are ".scalar(@alpha)." letters in the alphabet!";
findlength.pl:
26
20
26
There are 20 numerical elements
There are 26 letters in the alphabet!
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.
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 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
|
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:
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:
Larry David Roger Ken Michael Tom
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 "$firststring<br />";
print "$secondstring";
join.pl:
Pizza Steak Chicken Burgers
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:
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";
Display:
Pizza Steak burgers chicken
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";
Display:
PERL - If Statement Syntax
If statements are conditional statements used to test whether or not some condition is met and then continue executing the script. The syntax for an if statement has a specific flow to it - if(conditional_statment) { code to execute; }.PERL - If Conditional Statements
Conditional statements may involve logical operators and usually test equality or compare one value to another. Here's a look at some common conditional statements. Remember that the code to be executed will only execute if the condition in parentheses is met.ifs.pl:
#!/usr/bin/perl
# HTTP HEADER
print "content-type: text/html \n\n";
# SOME VARIABLES
$x = 7;
$y = 7;
# TESTING...ONE, TWO...TESTING
if ($x == 7) {
print '$x is equal to 7!';
print "<br />";
}
if (($x == 7) || ($y == 7)) {
print '$x or $y is equal to 7!';
print "<br />";
}
if (($x == 7) && ($y == 7)) {
print '$x and $y are equal to 7!';
print "<br />";
}
if.pl:
$x or $y is equal to 7!
$x and $y are equal to 7!
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 Loops
A for loop counts through a range of numbers, running a block of code each time it iterates through the loop. The syntax is for($start_num, Range, $increment) { code to execute }. A for loop needs 3 items placed inside of the conditional statement to be successful. First a starting point, then a range operator, and finally the incrementing value. Below is the example.forloop.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n";
# SET UP THE HTML TABLE
print "<table border='1'>";
# START THE LOOP, $i is the most common counter name for a loop!
for($i = 1; $i < 5; $i++) {
# PRINT A NEW ROW EACH TIME THROUGH W/ INCREMENT
print "<tr><td>$i</td><td>This is row $i</td></tr>";
}
# FINISH THE TABLE
print "</table>";
forloop.pl:
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
|
PERL - Foreach Loops
Foreach is designed to work with arrays. Say you want to execute some code foreach element within an array. Here's how you might go about it.foreachloop.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
# SET UP THE HTML TABLE
print "<table border='1'>";
# CREATE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
# SET A COUNT VARIABLE
$count = 1;
# BEGIN THE LOOP
foreach $names(@names) {
print "<tr><td>$count</td><td>$names</td></tr>";
$count++;
}
print "</table>";
foreachloop.pl:
1
|
Steve
|
2
|
Bill
|
3
|
Connor
|
4
|
Bradley
|
PERL - While
While loops continually iterate as long as the conditional statement remains true. It is very easy to write a conditional statement that will run forever especially at the beginner level of coding. On a more positive note, while loops are probably the easiest to understand. The syntax is while (conditional 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:
1
2
3
4
5
6
7
Finished Counting!
PERL - Next, Last, and Redo
Outlined below are several interrupts that can be used to redo or even skip iterations of code. These functions allow you to control the flow of your while loops.flowcontrol.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n";
# SET A VARIABLE
$count = 0;
while ($count <= 7) {
# SET A CONDITIONAL STATEMENT TO INTERRUPT @ 4
if ($count == 4) {
print "Skip Four!<br />";
next;
}
# PRINT THE COUNTER
print $count."<br />";
}
continue {
$count++;
};
print "Loop Finished!";
flowcontrol.pl:
1
2
3
Skip Four!
5
6
7
Finished Counting!
PERL - While Array Loop
Here we are just showing a method of looping through an array using a while loop. We use three variables to do this including: the array, a counter, and an index number so that each time the while loop iterates we also loop through each index of the array.whilearrayloop.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n";
# SET UP AN HTML TABLE
print "<table border='1'>";
# DEFINE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
# COUNTER - COUNTS EACH ROW
$count = 1;
# COUNTS EACH ELEMENT OF THE ARRAY
$n = 0;
# USE THE SCALAR FORM OF ARRAY
while ($names[$n]) {
print "<tr><td>$count</td><td>$names[$n]</td></tr>";
$n++;
$count++;
}
print "</table>";
while.pl:
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;
Display:
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:
Dime, 10
Quarter, 25
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
|
Values
|
Nickel
|
5
|
Dime
|
10
|
Quarter
|
25
|
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:
Nickel: 5
Quarter: 25
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:
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
Quarter, 0.25
Nickel, 0.05
Dime, 0.1
HalfDollar, 0.5
Penny, 0.01
Quarter, 0.25
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:
Dime, 0.1
HalfDollar, 0.5
Penny, 0.01
Quarter, 0.25
Nickel, 0.05
Dime, 0.1
Quarter, 0.25
PERL FILE MANAGEMENT...............
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 MYSITE!";
close (HANDLE);
PERL - Files and the die Function
The die function exists in several programming languages. It is used to kill your scripts and helps pinpoint where/if your code is failing. We use this function as follows.PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$filepath = "myhtml.html";
sysopen (HTML, '$filepath', O_RDWR|O_EXCL|O_CREAT, 0755) or die "$filepath cannot be opened.";
printf HTML "<html>\n";
printf HTML "<head>\n";
printf HTML "<title>My Home Page</title>";
printf HTML "</head>\n";
printf HTML "<body>\n";
printf HTML "<p align='center'>Here we have an HTML
page with a paragraph.</p>";
printf HTML "</body>\n";
printf HTML "</html>\n";
close (HTML);
Now if for some reason PERL is unable to open or create our
file, we will be told. It is good practice to use the die function and we will
be using it more as we dive deeper into file handling.Perl - 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.
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
|
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
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:
<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:
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 - 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:
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 line 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!
|
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 - Deleting Files
Use the unlink function to delete specific files from your web server. The best solution is often to set a variable name equal to the URL of the file you wish to delete.PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
print "File deleted successfully.";
} else {
print "File was not deleted.";
}
deletefiles.pl:
PERL - Removing Multiple Files at Once
Multiple files can be removed at once if we first create an array of files to be deleted and then loop through each one. There are several ways to go about this process.PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
@files = ("newtext.txt","moretext.txt","yetmoretext.txt");
foreach $file (@files) {
unlink($file);
}
Perl Command...............
PERL - User Input
PERL is capable of quickly taking input from a user then manipulating it in some fashion and spitting out some sort of result. Whether the task at hand is complex file manipulation or just a simple conversion script, your script may require some sort of user-input. With PERL this input comes from the command prompt or MS-DOS on a windows machine.In a minute we will be taking a look at how to retrieve some user input via the command prompt but first, you may need to install a PERL compiler for your machine.
ActivePERL - PERL for Windows
PERL comes pre-installed on many operating systems, like Linux for example. For those of us running a version of Windows however, we must download and install some sort of program that allows us to access PERL scripts from DOS. There are many PERL compilations available for your machine. A simple Google search yields several million results.ActivePERL is the simplest of installers available and it is also free to download. Download the program, follow the onscreen installation guide, and you should have an active installation of PERL ready to go.
To test the installation, make sure the program has fully completed installation and then run through the following:
- Click on Start, go to Run.
- Enter Command or cmd into the display box.
- At the command prompt type perl -v.
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!:
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 - <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?:
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:
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:
PERL DATABASE....
- DBI
- DBD::mysql
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 - 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
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 queryPERL - 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.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 - 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 = $connect->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>";
0 comments:
Post a Comment