setting

Web Designing Plateform: Introdused from Perl

Introdused from Perl



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

Hello, Perl!
You should see "Hello, Perl!" in the top left corner of your browser. If you have a problem, ask about it on the Perl Forum

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:

David paid $4.34 for Larry's shirt.
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:

5
2 ** 8
Hello, Perl!
Hello, Perl!
Scalars are very straight forward. Notice that we used a period (.) between each of our variables. This is a special kind of operator that concatenates two or more variables.

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:

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

Dime10Nickle5Quarter25
Jerry45Vickie38Tom22
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 />";
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:

Original String: Hello, am I about to be manipulated?!
Offset of 7: am I about to be manipulated?!
substr() started at the 7th element (remember we count from 0) which was the "a" in "am" and returned the rest of the string and we stored it into $substringoffset. Play around with this function a little and get a feel for how offset works!
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:

Original String: Hello, am I about to be manipulated?!
Offset of 7 and length of 10: am I about
mystring is now: Hello, I want to be manipulated?!
The original string was changed, so be careful when using the replace value argument of substr(). However, it's a great tool to have in your arsenal, as changing strings in this manner is pretty common. Please play around with substr() for a while and make sure you understand it!

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

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 - 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
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"; #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 plus 9 is 90
81 minus 9 is 72
81 times 10 is 810
81 divided by 9 is 9
81 to the 5th is 3486784401
81 modulus 79 is 2

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 plus 10 is 15
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
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
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)...
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
$myvariable = "Hello,";
$Myvariable = " World";
 
#ADD TWO STRINGS TOGETHER
$string3 = "$myvariable $Myvariable";
 
print $string3;

Display:

Hello, World

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
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"; #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 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"; #HTTP HEADER
 
# DEFINE AN ARRAY WITHOUT QUOTES
@coins = qw(Quarter Dime Nickel);
print "@coins";

Display:

Quarter Dime Nickel

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:

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
Definition
push(@array, Element)
Adds to the end of an array
pop(@array)
Removes the last element of the array
unshift(@array, Element)
Adds to the beginning of an array
shift(@array)
Removes the first element of an array
delete $array[index]
Removes an element by index number
It is also possible to remove any element by its indexed number. Just remember to use the scalar form of the array when doing so.($)

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 "$firststring<br />";
print "$secondstring";

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

Display:

burgers chicken pizza steak
Pizza Steak burgers chicken
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";

Display:

burgers chicken pizza steak
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 Statement Syntax

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

PERL - If Conditional Statements

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

ifs.pl:

#!/usr/bin/perl
 
# HTTP HEADER
print "content-type: text/html \n\n";
 
# SOME VARIABLES
$x = 7;
$y = 7;
 
# TESTING...ONE, TWO...TESTING
if ($x == 7) {
        print '$x is equal to 7!';
        print "<br />";
}
if (($x == 7) || ($y == 7)) {
        print '$x or $y is equal to 7!';
        print "<br />";
}
if (($x == 7) && ($y == 7)) {
        print '$x and $y are equal to 7!';
        print "<br />";
}

if.pl:

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

PERL - If Else

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

ifelse.pl:

#!/usr/bin/perl
 
# HTTP HEADER
print "content-type: text/html \n\n";
 
# SOME VARIABLES
$name = "Sarah";
$x = 5;
 
# IF/ELSE STATEMENTS
if ($x > 10) {
        print "$x is greater than 10!";
} else {
        print "$x is not greater than 10!";
}
print "<br />";
 
# STRINGS ARE A LITTLE DIFFERENT
if ($name eq "Sarah") {
        print "Hello, $name!";
} else {
        print "You are not $name!";
}

PERL - Elsif Statements

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

elsif.pl:

#!/usr/bin/perl
 
# HTTP HEADER
print "content-type: text/html \n\n";
 
# SOME VARIABLES
$x = 5;
 
# PLAY THE GUESSING GAME
if ($x == 6) {
        print "X must be 6.";
}
elsif ($x == 4) {
        print "X must be 4.";
}
elsif ($x == 5) {
        print "X must be 5!";
}
We could take this example a step further, adding an else statement at the bottom. This would serve as a catch all if none of the conditions were met.

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
We looped through one variable and incremented it. Using HTML, we were able to make a nice table to demonstrate our results.

PERL - Foreach Loops

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

foreachloop.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n"; #The header
 
# SET UP THE HTML TABLE
print "<table border='1'>";
 
# CREATE AN ARRAY 
@names = qw(Steve Bill Connor Bradley);
 
# SET A COUNT VARIABLE
$count = 1;
 
# BEGIN THE LOOP
foreach $names(@names) {
        print "<tr><td>$count</td><td>$names</td></tr>";
        $count++;
}
print "</table>";

foreachloop.pl:

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

0
1
2
3
4
5
6
7
Finished Counting!

PERL - Next, Last, and Redo

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

flowcontrol.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# SET A VARIABLE
$count = 0;
while ($count <= 7) {
               
        # SET A CONDITIONAL STATEMENT TO INTERRUPT @ 4
        if ($count == 4) {
               print "Skip Four!<br />";
               next;
        }
        # PRINT THE COUNTER
        print $count."<br />";
 
}
        continue {
               $count++;
        };
print "Loop Finished!";

flowcontrol.pl:

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

PERL - While Array Loop

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

 

whilearrayloop.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# SET UP AN HTML TABLE
print "<table border='1'>";
 
# DEFINE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
 
# COUNTER - COUNTS EACH ROW
$count = 1;
 
# COUNTS EACH ELEMENT OF THE ARRAY
$n = 0;
 
# USE THE SCALAR FORM OF ARRAY
while ($names[$n]) {
        print "<tr><td>$count</td><td>$names[$n]</td></tr>";
        $n++;
        $count++;
}
print "</table>";

while.pl:

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:

Nickel5Dime10Quarter25

PERL - Hash Indexing

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

legiblehash.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# DEFINE A HASH
%coins = ( "Quarter" , 25,
           "Dime" ,    10,
           "Nickel",    5 );
           
# LOOP THROUGH IT
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

legiblehash.pl:

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

tablehashes.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# DEFINE A HASH
%coins = ( "Quarter" , 25,
           "Dime" ,    10,
           "Nickel",    5 );
 
# SET UP THE TABLE
print "<table border='1'>";
print "<th>Keys</th><th>Values</th>";
 
# EXECUTE THE WHILE LOOP
while (($key, $value) = each(%coins)){
     print "<tr><td>".$key."</td>";
     print "<td>".$value."</td></tr>";
}
print "</table>";

tablehashes.pl:

Keys
Values
Nickel
5
Dime
10
Quarter
25
We have yet to sort our hash so you may experience different arrangements of your keys than shown in the display box.

PERL - Sorting Hashes by Key

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

sortkeys.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# DEFINE A HASH
%coins = ( "Quarter" , 25,
           "Dime" ,    10,
           "Nickel",    5 );
# FOREACH LOOP
foreach $key (sort keys %coins) {
     print "$key: $coins{$key}<br />";
}

sortkeys.pl:

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

PERL - Sorting Hashes by Value

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

sortvalues.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# DEFINE A HASH
%coins = ( "Quarter" , .25,
           "Dime" , .10,
           "Nickel", .05 );
# FOREACH LOOP
foreach $value (sort {$coins{$a} cmp $coins{$b} }
           keys %coins)
{
     print "$value $coins{$value}<br />";
}

sortvalues.pl:

Nickel 0.05
Dime 0.1
Quarter 0.25

PERL - Add an Element

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

addelements.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# BEGINNING HASH
%coins = ( "Quarter" , .25,
           "Dime" ,    .10,
           "Nickel",   .05 );
# PRINT THE OLD HASH
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}
 
# ADD NEW ELEMENT PAIRS
$coins{Penny} = .01;
$coins{HalfDollar} = .50;
 
# PRINT THE NEW HASH
print "<br />";
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

addelements.pl:

Nickel, 0.05
Dime, 0.1
Quarter, 0.25

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

PERL - Remove an Element

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

removeelements.pl:

#!/usr/bin/perl
 
print "content-type: text/html \n\n";
 
# DEFINED HASH
%coins = ( "Quarter" , .25,
           "HalfDollar" ,    .50,
           "Penny" ,    .01,
           "Dime" ,    .10,
           "Nickel",   .05 );
 
# PRINT OLD HASH
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}
 
# DELETE THE ELEMENT PAIRS
delete($coins{Penny});
delete($coins{HalfDollar});
 
# PRINT THE NEW HASH
print "<br />";
while (($key, $value) = each(%coins)){
     print $key.", ".$value."<br />";
}

removeelements.pl:

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

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

No comments:

Copyright © Web Designing Plateform Urang-kurai