0% found this document useful (0 votes)
92 views

Introduction To Perl:: #!c:/xampp/perl/bin/perl - Exe

The document provides an introduction and overview of the Perl programming language. It discusses that Perl was created in 1987 and has become a powerful tool for web development due to its flexibility, portability, and features. It describes how Perl scripts are created and saved with a .pl file extension. It also provides a basic "Hello World" example Perl script. Additionally, it covers Perl syntax including variables, arrays, hashes, strings, comments, escaping characters, and basic mathematical functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Introduction To Perl:: #!c:/xampp/perl/bin/perl - Exe

The document provides an introduction and overview of the Perl programming language. It discusses that Perl was created in 1987 and has become a powerful tool for web development due to its flexibility, portability, and features. It describes how Perl scripts are created and saved with a .pl file extension. It also provides a basic "Hello World" example Perl script. Additionally, it covers Perl syntax including variables, arrays, hashes, strings, comments, escaping characters, and basic mathematical functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Introduction to Perl:

 Created in 1987 by Larry Wall, the UNIX based language has evolved into a powerful tool for the internet.
 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.

Perl File Extension:


 A PERL script can be created inside of any normal simple-text editor program.
 PERL file must be saved with a .pl (.PL) file extension in order to be recognized as a functioning
PERL script.

Perl First Script:


 The first line of every PERL script is a commented line directed toward the PERL interpreter.

 #!C:\xampp\perl\bin\perl.exe
 Perl understands to working with a web browser.
 print "content-type: text/html \n\n";
Example program --- helloperl.pl

#!C:\xampp\perl\bin\perl.exe
print "content-type: text/html \n\n";
print "Hello, Perl!";

output : Hello, Perl!

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.

$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.
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';

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

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

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 tizag.com!"; #String to be formatted
$newline = "welcome to \ntizag.com!";
$capital = "\uwelcome to tizag.com!";
$ALLCAPS = "\Uwelcome to tizag.com!";

# PRINT THE NEWLY FORMATTED STRINGS


print $mystring."<br />";
print $newline."<br />";
print $capital."<br />";
print $ALLCAPS;

Any combination of these special characters can be used at any time to properly punctuate your strings. They also come in handy when
printing out HTML with your PERL functions.

perl - substr() and string indexing


The substr() function 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 - mathematical functions


With numbers comes math. Simple arithmetic operations are discussed in thePERL 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 theMath::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
5 == 5
==,eq Test: Is 5 equal to 5? True
5 eq 5
7 != 2
!=,ne Test: Is 7 not equal to 2? True
7 ne 2
7<4
<,lt Test: Is 7 less than 4? False
7 lt 4
7>4
>,gt Test: Is 7 greater than 4? True
7 gt 4
7 <= 11
<=,le Test: Is 7 less than or equal to 11? True
7 le 11
7 >= 11
>=,ge Test: Is 7 greater than or equal to 11? False
7 ge 11

Logical
Operator Defined Example
&&,and Associates two variables using AND if (($x && $y) == 5)...
||,or Associates two variables using OR if (($x || $y) == 5)...

Please note that you must use each different operator depending of whether or not you are comparing strings or numbers. In the table
above, the black operators are for numbers and the red ones are for strings.

perl - variables + operators


Variables can be used with mathematical formulas using PERL Operatorsdiscussed 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 - 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 ifstatement 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.

orloop.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 codeforeach 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.

perl - file handling


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

perl - assigning handles


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

PERL Code:
#!/usr/bin/perl

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


$FilePath = "home/html/myhtml.html"
sysopen(HANDLE, $FilePath, O_RDWR);
printf HANDLE "Welcome to Tizag!";
close (HANDLE);

perl - files and the die function


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

PERL Code:
#!/usr/bin/perl

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

$filepath = "myhtml.html";

sysopen (HTML, '$filepath', O_RDWR|O_EXCL|O_CREAT, 0755) or die "$filepath cannot be opened.";


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

perl - file open


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

When opening files as a programmer, there will generally be one of three goals in mind, file creation, appending files, or trunicating files.

Create:
Checks to see if the file exists, if not, perl creates a new file.
Append:
Sets the pointer to the end of the file, all output following will be added onto the tail end of the file.
Truncate:
Overwrites your existing file with a new one, this means all data in the old file will be lost.
perl - open a file
The following example will open a previously saved HTML document.

PERL Code:
#!/usr/bin/perl

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

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

open(FH, $FilePath, permissions);


or
sysopen(FH, $FileName, permission);

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

perl - file permissions


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

Shorthand Flags:
Entities 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); orsysopen(FILEHANDLE, $filename, permissions, CHMOD);

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

PERL Code:
#!/usr/bin/perl
use Fcntl; #The Module

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


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

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

myhtml.html-browser view:

Here we have an HTML page with a paragraph.

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

PERL Code:
open(TEXT,+<newtext.txt.);
printf TEXT "Check out our text file!";
close (TEXT);

We use the printf function instead of print to actually print our text into the file. Everything inside the printf function is embeded into our
created file.

perl - reading from a file


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

PERL Code:
#!/usr/bin/perl

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


$HTML = "myhtml.html";
open (HTML) or die "Can't open the file!";
print <HTML>;
close (HTML);

myhtml.pl:

Here we have an HTML page with a paragraph.

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

perl - input array


PERL is able to print out lines of other files with the use of arrays. Following the example above when we called our HTML file handle
using the input operator, PERL automatically stored each 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!

Here we have an HTML page with a paragraph.

To permanently change a file, replace the print function with the printf function.

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:
File deleted successfully.

perl - removing multiple files at once


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

PERL Code:
#!/usr/bin/perl

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


@files = ("newtext.txt","moretext.txt","yetmoretext.txt");
foreach $file (@files) {
unlink($file);
}

perl - 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 - Special Variables


There are some variables which have a predefined and special meaning in
Perl. They are the variables that use punctuation characters after the usual
variable indicator ($, @, or %), such as $_ ( explained below ).
Most of the special variables have an english like long name, e.g., Operating
System Error variable $! can be written as $OS_ERROR. But if you are
going to use english like names, then you would have to put one line use
English; at the top of your program file. This guides the interpreter to
pickup exact meaning of the variable.

The most commonly used special variable is $_, which contains the default
input and pattern-searching string. For example, in the following lines −

#!/usr/bin/perl

foreach ('hickory','dickory','doc') {

print $_;

print "\n";

When executed, this will produce the following result −

hickory
dickory
doc

Again, let's check the same example without using $_ variable explicitly −

#!/usr/bin/perl

foreach ('hickory','dickory','doc') {

print;

print "\n";

When executed, this will also produce the following result −

hickory
dickory
doc

The first time the loop is executed, "hickory" is printed. The second time
around, "dickory" is printed, and the third time, "doc" is printed. That's
because in each iteration of the loop, the current string is placed in $_, and
is used by default by print. Here are the places where Perl will assume $_
even if you don't specify it −

 Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for
-t, which defaults to STDIN.

 Various list functions like print and unlink.


 The pattern-matching operations m//, s///, and tr/// when used without an =~ operator.

 The default iterator variable in a foreach loop if no other variable is supplied.

 The implicit iterator variable in the grep and map functions.

 The default place to put an input record when a line-input operation's result is tested by itself as the sole
criterion of a while test (i.e., ). Note that outside of a while test, this will not happen.

Special Variable Types


Based on the usage and nature of special variables we can categorize them
in the following categories −

 Global Scalar Special Variables.

 Global Array Special Variables.

 Global Hash Special Variables.

 Global Special Filehandles.

 Global Special Constants.

 Regular Expression Special Variables.

 Filehandle Special Variables.

Global Scalar Special Variables


Here is the list of all the scalar special variables. We have listed
corresponding english like names along with the symbolic names.

$_ The default input and


pattern-searching space.

$ARG

$ARGV Contains the name of the


current file when reading
from <ARGV>.

Global Array Special Variables


@ARGV The array containing the command-line
arguments intended for the script.

@INC The array containing the list of places to look


for Perl scripts to be evaluated by the do,
require, or use constructs.

@F The array into which the input lines are split


when the -a command-line switch is given.

Global Hash Special Variables


The hash containing entries for the filename of
%INC
each file that has been included via do or
require.

The hash containing your current environment.


%ENV

The hash used to set signal handlers for


%SIG
various signals.

Global Special Filehandles


The special filehandle that iterates over
ARGV
command line filenames in @ARGV. Usually
written as the null filehandle in <>.

The special filehandle for standard error in any


STDERR
package.

The special filehandle for standard input in any


STDIN
package.

The special filehandle for standard output in


STDOUT
any package.

The special filehandle that refers to anything


DATA
following the __END__ token in the file
containing the script. Or, the special filehandle
for anything following the __DATA__ token in a
required file, as long as you're reading data in
the same package __DATA__ was found in.

The special filehandle used to cache the


_ (underscore)
information from the last stat, lstat, or file test
operator.

Global Special Constants


Indicates the logical end of your program. Any
__END__
following text is ignored, but may be read via
the DATA filehandle.

Represents the filename at the point in your


__FILE__
program where it's used. Not interpolated into
strings.

Represents the current line number. Not


__LINE__
interpolated into strings.

Represents the current package name at


compile time, or undefined if there is no
__PACKAGE__
current package. Not interpolated into strings.

Perl - Subroutines
A Perl subroutine or function is a group of statements that together
performs a task. You can divide up your code into separate subroutines.
How you divide up your code among different subroutines is up to you, but
logically the division usually is so each function performs a specific task.

Perl uses the terms subroutine, method and function interchangeably.

Define and Call a Subroutine


The general form of a subroutine definition in Perl programming language is
as follows −

sub subroutine_name{
body of the subroutine
}

The typical way of calling that Perl subroutine is as follows −

subroutine_name( list of arguments );

In versions of Perl before 5.0, the syntax for calling subroutines was slightly
different as shown below. This still works in the newest versions of Perl, but
it is not recommended since it bypasses the subroutine prototypes.

&subroutine_name( list of arguments );

Let's have a look into the following example, which defines a simple
function and then call it. Because Perl compiles your program before
executing it, it doesn't matter where you declare your subroutine.

#!/usr/bin/perl

# Function definition
sub Hello{
print "Hello, World!\n";
}

# Function call
Hello();

When above program is executed, it produces the following result −

Hello, World!
Passing Arguments to a Subroutine
You can pass various arguments to a subroutine like you do in any other
programming language and they can be acessed inside the function using
the special array @_. Thus the first argument to the function is in $_[0],
the second is in $_[1], and so on.

You can pass arrays and hashes as arguments like any scalar but passing
more than one array or hash normally causes them to lose their separate
identities. So we will use references ( explained in the next chapter ) to
pass any array or hash.

Let's try the following example, which takes a list of numbers and then
prints their average −

#!/usr/bin/perl
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;

foreach $item (@_){


$sum += $item;
}
$average = $sum / $n;

print "Average for the given numbers : $average\n";


}

# Function call
Average(10, 20, 30);

When above program is executed, it produces the following result −

Average for the given numbers : 20

Passing Lists to Subroutines


Because the @_ variable is an array, it can be used to supply lists to a
subroutine. However, because of the way in which Perl accepts and parses
lists and arrays, it can be difficult to extract the individual elements from
@_. If you have to pass a list along with other scalar arguments, then make
list as the last argument as shown below −

#!/usr/bin/perl
# Function definition
sub PrintList{
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);

# Function call with list parameter


PrintList($a, @b);

When above program is executed, it produces the following result −

Given list is 10 1 2 3 4

Passing Hashes to Subroutines


When you supply a hash to a subroutine or operator that accepts a list, then
hash is automatically translated into a list of key/value pairs. For example −

#!/usr/bin/perl
# Function definition
sub PrintHash{
my (%hash) = @_;

foreach my $key ( keys %hash ){


my $value = $hash{$key};
print "$key : $value\n";
}
}
%hash = ('name' => 'Tom', 'age' => 19);

# Function call with hash parameter


PrintHash(%hash);

When above program is executed, it produces the following result −

name : Tom
age : 19

Returning Value from a Subroutine


You can return a value from subroutine like you do in any other
programming language. If you are not returning a value from a subroutine
then whatever calculation is last performed in a subroutine is automatically
also the return value.You can return arrays and hashes from the subroutine
like any scalar but returning more than one array or hash normally causes
them to lose their separate identities. So we will use references ( explained
in the next chapter ) to return any array or hash from a function.

Let's try the following example, which takes a list of numbers and then
returns their average −

#!/usr/bin/perl
# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;

foreach $item (@_){


$sum += $item;
}
$average = $sum / $n;

return $average;
}

# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";

When above program is executed, it produces the following result −

Average for the given numbers : 20

Private Variables in a Subroutine


By default, all variables in Perl are global variables, which means they can
be accessed from anywhere in the program. But you can
create private variables called lexical variables at any time with
the my operator.

The my operator confines a variable to a particular region of code in which


it can be used and accessed. Outside that region, this variable cannot be
used or accessed. This region is called its scope. A lexical scope is usually a
block of code with a set of braces around it, such as those defining the body
of the subroutine or those marking the code blocks of if, while, for,
foreach, and eval statements.

Following is an example showing you how to define a single or multiple


private variables using my operator −

sub somefunc {

my $variable; # $variable is invisible outside somefunc()

my ($another, @an_array, %a_hash); # declaring many variables at once

Let's check the following example to distinguish between global and private
variables −

#!/usr/bin/perl

# Global variable
$string = "Hello, World!";

# Function definition
sub PrintHello{
# Private variable for PrintHello function
my $string;
$string = "Hello, Perl!";
print "Inside the function $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";

When above program is executed, it produces the following result −

Inside the function Hello, Perl!


Outside the function Hello, World!

Temporary Values via local()


The local is mostly used when the current value of a variable must be
visible to called subroutines. A local just gives temporary values to global
(meaning package) variables. This is known asdynamic scoping. Lexical
scoping is done with my, which works more like C's auto declarations.

If more than one variable or expression is given to local, they must be


placed in parentheses. This operator works by saving the current values of
those variables in its argument list on a hidden stack and restoring them
upon exiting the block, subroutine, or eval.

Let's check the following example to distinguish between global and local
variables −

#!/usr/bin/perl

# Global variable
$string = "Hello, World!";

sub PrintHello{
# Private variable for PrintHello function
local $string;
$string = "Hello, Perl!";
PrintMe();
print "Inside the function PrintHello $string\n";
}
sub PrintMe{
print "Inside the function PrintMe $string\n";
}

# Function call
PrintHello();
print "Outside the function $string\n";

When above program is executed, it produces the following result −

Inside the function PrintMe Hello, Perl!


Inside the function PrintHello Hello, Perl!
Outside the function Hello, World!

State Variables via state()


There are another type of lexical variables, which are similar to private
variables but they maintain their state and they do not get reinitialized
upon multiple calls of the subroutines. These variables are defined using
the state operator and available starting from Perl 5.9.4.

Let's check the following example to demonstrate the use of state variables

#!/usr/bin/perl

use feature 'state';

sub PrintCount{
state $count = 0; # initial value

print "Value of counter is $count\n";


$count++;
}

for (1..5){
PrintCount();
}

When above program is executed, it produces the following result −

Value of counter is 0
Value of counter is 1
Value of counter is 2
Value of counter is 3
Value of counter is 4

Prior to Perl 5.10, you would have to write it like this −

#!/usr/bin/perl

{
my $count = 0; # initial value

sub PrintCount {
print "Value of counter is $count\n";
$count++;
}
}

for (1..5){
PrintCount();
}

Subroutine Call Context


The context of a subroutine or statement is defined as the type of return
value that is expected. This allows you to use a single function that returns
different values based on what the user is expecting to receive. For
example, the following localtime() returns a string when it is called in scalar
context, but it returns a list when it is called in list context.

my $datestring = localtime( time );

In this example, the value of $timestr is now a string made up of the


current date and time, for example, Thu Nov 30 15:21:33 2000. Conversely

($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time);

Now the individual variables contain the corresponding values returned by


localtime() subroutine.

Perl - Database Access


This chapter teaches you how to access a database inside your Perl script.
Starting from Perl 5 has become very easy to write database applications
using DBI module. DBI stands forDatabase Independent Interface for
Perl, which means DBI provides an abstraction layer between the Perl code
and the underlying database, allowing you to switch database
implementations really easily.

The DBI is a database access module for the Perl programming language. It
provides a set of methods, variables, and conventions that provide a
consistent database interface, independent of the actual database being
used.

Architecture of a DBI Application


DBI is independent of any database available in backend. You can use DBI
whether you are working with Oracle, MySQL or Informix, etc. This is clear
from the following architure diagram.
Here DBI is responsible of taking all SQL commands through the API, (i.e.,
Application Programming Interface) and to dispatch them to the appropriate
driver for actual execution. And finally, DBI is responsible of taking results
from the driver and giving back it to the calling scritp.

Notation and Conventions


Throughout this chapter following notations will be used and it is
recommended that you should also follow the same convention.

$dsn Database source name


$dbh Database handle object
$sth Statement handle object
$h Any of the handle types above ($dbh, $sth, or $drh)
$rc General Return Code (boolean: true=ok, false=error)
$rv General Return Value (typically an integer)
@ary List of values returned from the database.
$rows Number of rows processed (if available, else -1)
$fh A filehandle
undef NULL values are represented by undefined values in Perl
\%attr Reference to a hash of attribute values passed to methods

Database Connection
Assuming we are going to work with MySQL database. Before connecting to
a database make sure of the followings. You can take help of our MySQL
tutorial in case you are not aware about how to create database and tables
in MySQL database.

 You have created a database with a name TESTDB.

 You have created a table with a name TEST_TABLE in TESTDB.

 This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

 User ID "testuser" and password "test123" are set to access TESTDB.

 Perl Module DBI is installed properly on your machine.


 You have gone through MySQL tutorial to understand MySQL Basics.

Following is the example of connecting with MySQL database "TESTDB" −

#!/usr/bin/perl

use DBI
use strict;

my $driver = "mysql";
my $database = "TESTDB";
my $dsn = "DBI:$driver:database=$database";
my $userid = "testuser";
my $password = "test123";

my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

If a connection is established with the datasource then a Database Handle is


returned and saved into $dbh for further use otherwise $dbh is set
to undef value and $DBI::errstr returns an error string.

INSERT Operation
INSERT operation is required when you want to create some records into a
table. Here we are using table TEST_TABLE to create our records. So once
our database connection is established, we are ready to create records into
TEST_TABLE. Following is the procedure to create single record into
TEST_TABLE. You can create as many as records you like using the same
concept.

Record creation takes the following steps−

 Prearing SQL statement with INSERT statement. This will be done using prepare() API.

 Executing SQL query to select all the results from the database. This will be done using execute() API.

 Releasing Stattement handle. This will be done usingfinish() API.

 If everything goes fine then commit this operation otherwise you can rollback complete transaction.
Commit and Rollback are explained in next sections.

my $sth = $dbh->prepare("INSERT INTO TEST_TABLE


(FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
values
('john', 'poul', 'M', 30, 13000)");
$sth->execute() or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;

Using Bind Values


There may be a case when values to be entered is not given in advance. So
you can use bind variables which will take the required values at run time.
Perl DBI modules make use of a question mark in place of actual value and
then actual values are passed through execute() API at the run time.
Following is the example −

my $first_name = "john";
my $last_name = "poul";
my $sex = "M";
my $income = 13000;
my $age = 30;
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
(FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
values
(?,?,?,?)");
$sth->execute($first_name,$last_name,$sex, $age, $income)
or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;

READ Operation
READ Operation on any databasse means to fetch some useful information
from the database, i.e, one or more records from one or more tables. So
once our database connection is established, we are ready to make a query
into this database. Following is the procedure to query all the records
having AGE greater than 20. This will take four steps −

 Prearing SQL SELECT query based on required conditions. This will be done using prepare() API.

 Executing SQL query to select all the results from the database. This will be done using execute() API.

 Fetching all the results one by one and printing those results.This will be done
using fetchrow_array() API.

 Releasing Stattement handle. This will be done usingfinish() API.


my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME
FROM TEST_TABLE
WHERE AGE > 20");
$sth->execute() or die $DBI::errstr;
print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
my ($first_name, $last_name ) = @row;
print "First Name = $first_name, Last Name = $last_name\n";
}
$sth->finish();

Using Bind Values


There may be a case when condition is not given in advance. So you can
use bind variables, which will take the required values at run time. Perl DBI
modules makes use of a question mark in place of actual value and then the
actual values are passed through execute() API at the run time. Following is
the example −

$age = 20;

my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME

FROM TEST_TABLE

WHERE AGE > ?");

$sth->execute( $age ) or die $DBI::errstr;

print "Number of rows found :" + $sth->rows;

while (my @row = $sth->fetchrow_array()) {

my ($first_name, $last_name ) = @row;

print "First Name = $first_name, Last Name = $last_name\n";

$sth->finish();

UPDATE Operation
UPDATE Operation on any database means to update one or more records
already available in the database tables. Following is the procedure to
update all the records having SEX as 'M'. Here we will increase AGE of all
the males by one year. This will take three steps −

 Prearing SQL query based on required conditions. This will be done using prepare() API.

 Executing SQL query to select all the results from the database. This will be done using execute() API.

 Releasing Stattement handle. This will be done usingfinish() API.


 If everything goes fine then commit this operation otherwise you can rollback complete transaction. See
next section for commit and rollback APIs.

my $sth = $dbh->prepare("UPDATE TEST_TABLE

SET AGE = AGE + 1

WHERE SEX = 'M'");

$sth->execute() or die $DBI::errstr;

print "Number of rows updated :" + $sth->rows;

$sth->finish();

$dbh->commit or die $DBI::errstr;

Using Bind Values


There may be a case when condition is not given in advance. So you can
use bind variables, which will take required values at run time. Perl DBI
modules make use of a question mark in place of actual value and then the
actual values are passed through execute() API at the run time. Following is
the example −

$sex = 'M';

my $sth = $dbh->prepare("UPDATE TEST_TABLE

SET AGE = AGE + 1

WHERE SEX = ?");

$sth->execute('$sex') or die $DBI::errstr;

print "Number of rows updated :" + $sth->rows;

$sth->finish();

$dbh->commit or die $DBI::errstr;

In some case you would like to set a value, which is not given in advance so
you can use binding value as follows. In this example income of all males
will be set to 10000.

$sex = 'M';

$income = 10000;

my $sth = $dbh->prepare("UPDATE TEST_TABLE

SET INCOME = ?

WHERE SEX = ?");

$sth->execute( $income, '$sex') or die $DBI::errstr;

print "Number of rows updated :" + $sth->rows;

$sth->finish();

DELETE Operation
DELETE operation is required when you want to delete some records from
your database. Following is the procedure to delete all the records from
TEST_TABLE where AGE is equal to 30. This operation will take the
following steps.

 Prearing SQL query based on required conditions. This will be done using prepare() API.

 Executing SQL query to delete required records from the database. This will be done
using execute() API.

 Releasing Stattement handle. This will be done usingfinish() API.

 If everything goes fine then commit this operation otherwise you can rollback complete transaction.

$age = 30;

my $sth = $dbh->prepare("DELETE FROM TEST_TABLE

WHERE AGE = ?");

$sth->execute( $age ) or die $DBI::errstr;

print "Number of rows deleted :" + $sth->rows;

$sth->finish();

$dbh->commit or die $DBI::errstr;

perl - mysql module


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

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

perl - mysql config


Before we dive head first into the functions, we may want to set up some config variables that we will be calling upon in each script to
first connect to our database. Have the following information easily accessible.

 Our Web Host's data source name (DSN)


 User Name for the MySQL Database
 Password for the MySQL Database
 Name of Database
 Name of Table(s)

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

# PERL MODULE WE WILL BE USING


use Mysql;

# MySQL CONFIG VARIABLES


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

perl - mysql connect


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

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

# PERL MODULE
use Mysql;

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

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

# PERL MYSQL CONNECT


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

If this script was run on your web server through a web browser, you should be starring at a blank white screen and all is well.

perl - mysql listdbs()


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

listdbs.pl:
@databases = $connect->listdbs;

We can then loop through this array and print out our results to the browser.

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

# PERL MODULES
use Mysql;

# MYSQL CONFIG VARIABLES


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

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

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

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

Perl - CGI Programming


What is CGI ?
 A Common Gateway Interface, or CGI, is a set of standards that
defines how information is exchanged between the web server and a
custom script.

 The CGI specifications are currently maintained by the NCSA and


NCSA defines CGI is as follows −

The Common Gateway Interface, or CGI, is a standard for external


gateway programs to interface with information servers such as HTTP
servers.

 The current version is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing
To understand the concept of CGI, lets see what happens when we click a
hyper link available on a web page to browse a particular web page or URL.

 Your browser contacts web server using HTTP protocol and demands for the URL,
i.e., web page filename.

 Web Server will check the URL and will look for the filename requested. If web
server finds that file then it sends the file back to the browser without any further
execution otherwise sends an error message indicating that you have requested a
wrong file.

 Web browser takes response from web server and displays either the received file
content or an error message in case file is not found.
However, it is possible to set up HTTP server in such a way so that
whenever a file in a certain directory is requested that file is not sent back;
instead it is executed as a program, and whatever that program outputs as
a result, that is sent back for your browser to display. This can be done by
using a special functionality available in the web server and it is
called Common Gateway Interface or CGI and such programs which are
executed by the server to produce final result, are called CGI scripts. These
CGI programs can be a PERL Script, Shell Script, C or C++ program, etc.

CGI Architecture Diagram

Web Server Support and Configuration


Before you proceed with CGI Programming, make sure that your Web
Server supports CGI functionality and it is configured to handle CGI
programs. All the CGI programs to be executed by the web server are kept
in a pre-configured directory. This directory is called CGI directory and by
convention it is named as /cgi-bin. By convention Perl CGI files will have
extension as .cgi.

First CGI Program


Here is a simple link which is linked to a CGI script calledhello.cgi. This file
has been kept in /cgi-bin/ directory and it has the following content.
Before running your CGI program, make sure you have change mode of file
using chmod 755 hello.cgiUNIX command.

#!/usr/bin/perl

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

print '<html>';

print '<head>';
print '<title>Hello Word - First CGI Program</title>';

print '</head>';

print '<body>';

print '<h2>Hello Word! This is my first CGI program</h2>';

print '</body>';

print '</html>';

1;

Now if you click hello.cgi link then request goes to web server who search
for hello.cgi in /cgi-bin directory, execute it and whatever result got
generated, web server sends that result back to the web browser, which is
as follows −

Hello Word! This is my first CGI program

This hello.cgi script is a simple Perl script which is writing its output on
STDOUT file, i.e., screen. There is one important and extra feature available
which is first line to be printed Content-type:text/html\r\n\r\n. This
line is sent back to the browser and specifies the content type to be
displayed on the browser screen. Now you must have understood basic
concept of CGI and you can write many complicated CGI programs using
Perl. This script can interact with any other external system also to
exchange information such as a database, web services, or any other
complex interfaces.

GET and POST Methods


You must have come across many situations when you need to pass some
information from your browser to the web server and ultimately to your CGI
Program handling your requests. Most frequently browser uses two methods
to pass this information to the web server. These methods are GET Method
and POSTMethod. Let's check them one by one.

Passing Information using GET Method


The GET method sends the encoded user information appended to the page
URL itself. The page and the encoded information are separated by the ?
character as follows −

http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2
The GET method is the defualt method to pass information from a browser
to the web server and it produces a long string that appears in your
browser's Location:box. You should never use GET method if you have
password or other sensitive information to pass to the server. The GET
method has size limitation: only 1024 characters can be passed in a request
string.

This information is passed using QUERY_STRING header and will be


accessible in your CGI Program through QUERY_STRING environment
variable which you can parse and use in your CGI program.

You can pass information by simply concatenating key and value pairs
alongwith any URL or you can use HTML <FORM> tags to pass information
using GET method.

Simple URL Example: Get Method


Here is a simple URL which will pass two values to hello_get.cgi program
using GET method.
http://www.tutorialspoint.com/cgi-bin/hello_get.cgi?first_name=ZARA&last_name=ALI

Below is hello_get.cgi script to handle input given by web browser.

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);


# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "</head>";
print "<body>";
print "<h2>Hello $first_name $last_name - Second CGI Program</h2>";
print "</body>";
print "</html>";

1;

Simple FORM Example: GET Method


Here is a simple example, which passes two values using HTML FORM and
submit button. We are going to use the same CGI script hello_get.cgi to
handle this input.

<FORM action="/cgi-bin/hello_get.cgi" method="GET">


First Name: <input type="text" name="first_name"> <br>

Last Name: <input type="text" name="last_name">


<input type="submit" value="Submit">
</FORM>

Here is the actual output of the above form coding. Now you can enter First
and Last Name and then click submit button to see the result.

First Name:

Submit
Last Name:

Passing Information using POST Method


A more reliable method of passing information to a CGI program is
the POST method. This packages the information in exactly the same way
as GET methods, but instead of sending it as a text string after a ? in the
URL, it sends it as a separate message as a part of HTTP header. Web
server provides this message to the CGI script in the form of the standard
input.
Below is the modified hello_post.cgi script to handle input given by the
web browser. This script will handle GET as well as POST method.

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);


# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$first_name = $FORM{first_name};
$last_name = $FORM{last_name};

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "</head>";
print "<body>";
print "<h2>Hello $first_name $last_name - Second CGI Program</h2>";
print "</body>";
print "</html>";

1;
Let us take again same example as above, which passes two values using
HTML FORM and submit button. We are going to use CGI script
hello_post.cgi to handle this input.

<FORM action="/cgi-bin/hello_post.cgi" method="POST">


First Name: <input type="text" name="first_name"> <br>

Last Name: <input type="text" name="last_name">

<input type="submit" value="Submit">


</FORM>

Here is the actual output of the above form coding, You enter First and Last
Name and then click submit button to see the result.

First Name:

Submit
Last Name:

Passing Checkbox Data to CGI Program


Checkboxe are used when more than one option is required to be selected.
Here is an example HTML code for a form with two checkboxes.

<form action="/cgi-bin/checkbox.cgi" method="POST" target="_blank">


<input type="checkbox" name="maths" value="on"> Maths
<input type="checkbox" name="physics" value="on"> Physics
<input type="submit" value="Select Subject">
</form>

The result of this code is the following form −

Select Subject
Maths Physics

Below is checkbox.cgi script to handle input given by web browser for


radio button.

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);


# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
if( $FORM{maths} ){
$maths_flag ="ON";
}else{
$maths_flag ="OFF";
}
if( $FORM{physics} ){
$physics_flag ="ON";
}else{
$physics_flag ="OFF";
}

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Checkbox - Third CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> CheckBox Maths is : $maths_flag</h2>";
print "<h2> CheckBox Physics is : $physics_flag</h2>";
print "</body>";
print "</html>";

1;

Passing Radio Button Data to CGI Program


Radio Buttons are used when only one option is required to be selected.
Here is example HTML code for an form with two radio button −

<form action="/cgi-bin/radiobutton.cgi" method="POST" target="_blank">


<input type="radio" name="subject" value="maths"> Maths
<input type="radio" name="subject" value="physics"> Physics
<input type="submit" value="Select Subject">
</form>

The result of this code is the following form:

Select Subject
Maths Physics

Below is radiobutton.cgi script to handle input given by the web browser


for radio button.

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);


# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{subject};

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Radio - Fourth CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> Selected Subject is $subject</h2>";
print "</body>";
print "</html>";

1;

Passing Text Area Data to CGI Program


A textarea element is used when multiline text has to be passed to the CGI
Program. Here is an example HTML code for a form with a TEXTAREA box −

<form action="/cgi-bin/textarea.cgi" method="POST" target="_blank">


<textarea name="textcontent" cols=40 rows=4>
Type your text here...
</textarea>
<input type="submit" value="Submit">
</form>

The result of this code is the following form −

Submit
Below is the textarea.cgi script to handle input given by the web browser.

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);


# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$text_content = $FORM{textcontent};

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> Entered Text Content is $text_content</h2>";
print "</body>";
print "</html>";
1;

Passing Drop Down Box Data to CGI Program


A drop down box is used when we have many options available but only one
or two will be selected. Here is example HTML code for a form with one drop
down box.

<form action="/cgi-bin/dropdown.cgi" method="POST" target="_blank">


<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
<input type="submit" value="Submit">
</form>

The result of this code is the following form −

Maths Submit

Below is the dropdown.cgi script to handle input given by web browser.

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);


# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%(..)/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
$subject = $FORM{dropdown};

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Dropdown Box - Sixth CGI Program</title>";
print "</head>";
print "<body>";
print "<h2> Selected Subject is $subject</h2>";
print "</body>";
print "</html>";

1;

LAB PROGRAMS
14. Write a program which illustrates the use of associative arrays in perl.

perl_associative.pl
print "Enter number of Employee";
$n=<STDIN>;

$j=1;
while($j<$n+1)
{
print "\nEnter name and age of Employee",$j;
$name =<STDIN>;
$val{$name}=<STDIN>;

$j=$j+1;
}

print "\n*****Details of Employee*****\n";

$j=1;
while (($key,$value) = each %val)
{
print "\nEmployee:","->";
#chomp funtion removes newline character from end of the string
chomp $key;
print "name=$key ,age=$value\n";
$j=$j+1;
}
OUTPUT:--
15. Write perl program takes a set names along the command line and prints whether
they are
regular files or special files

command-line.pl

foreach (@ARGV) { #@ARGV receives command line arguments

print;

print((-f) ? " -REGULAR\n" : " -SPECIAL\n") #using file test


operator -f

}
OUTPUT:--

16. Write a perl program to implement UNIX `passwd' program

Hello.pl

use Term::ReadKey;
use File::Slurp;
#slurp mode - reading a file in one step
#install the module ReadKey=>To not echo password back to <STDIN>
#The chomp() function will remove (usually) any newline character from the end of a
string.
#The standard Unix command to change your password is: passwd

print 'Enter User name=>';


chomp($user=<STDIN>);
#print 'Enter password=>';
#$ps=<>;

print "Enter your password:";


ReadMode('noecho'); # don't echo
chomp($password = <STDIN>);
ReadMode(0); #to get back to previous mode

$str=$user.":".$password ;

open(PSFILE,"<", "psfile.txt") or die "Can't find file";


#print "\nFile opening is successfull";

if (grep{/$str/} <PSFILE>)
{
print "\n\nWELCOME...",$user,"\n";
print "\n Do you wish to change ur password(y/n):";
chomp($flag=<STDIN>);
if($flag eq 'y') #eq is to compare strings &'==' to compare numbers
{
print "Enter old password:";
ReadMode('noecho'); # don't echo
chomp($old = <STDIN>);

if($old eq $password) #check wether old password =original


password
{
print "\nEnter new password:"; #reading new password
ReadMode('noecho'); # don't echo
chomp($new= <STDIN>);
ReadMode(0);

$text = read_file('psfile.txt'); #saving the content of password


file as string
close(PSFILE);
open(PSFILE,">", "psfile.txt") ; #opening password file in write
mode
$text =~ s/$old/$new/g; #finding and replacing old
password with new password
write_file( 'psfile.txt', $text ) ; #writing the modified content in to
file
close(PSFILE);
print "\n\n**password changed successfully**\n";
}
else
{
print "\n Invalid password\n";
exit 0;
}

close(PSFILE);
}
else
{
close(PSFILE);
exit 0;
}
}
else
{
print "\nGiven Username and password is not valid\n";
}

Psfile.txt
teacher:CSE
student:linux
loyola:CSE
android:java

OUTPUT:--
17. An example perl program to connect to a MySQl database table and executing
simple
commands.

Perldb.pl

#!C:\xampp\perl\bin\perl.exe

use DBI;
use strict;

my $driver = "mysql";
my $database = "user";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password ) or die
$DBI::errstr;

my $sth = $dbh->prepare("create table emp1(FIRST_NAME


VARCHAR(20),LAST_NAME VARCHAR(20),GENDER VARCHAR(20),AGE
int(11),INCOME int(11))") or die $DBI::errstr;

$sth->execute();

print 'Enter number of employees=';


chomp(my $no=<STDIN>);
for (my $i=1; $i <= $no; $i++)

{
print "Enter deatils of employee:$i\n";
print ' Enter FIRST_NAME:';
chomp(my $fn=<STDIN>);
print 'Enter LAST_NAME:';
chomp(my $ln=<STDIN>);
print 'Enter GENDER:';
chomp(my $g=<STDIN>);
print 'Enter AGE:';
chomp(my $age=<STDIN>);
print 'Enter INCOME:';
chomp(my $income=<STDIN>);

my $sth = $dbh->prepare("INSERT INTO emp1(FIRST_NAME, LAST_NAME,


GENDER, AGE, INCOME ) values (?,?,?,?,?)");

$sth->execute($fn,$ln,$g, $age, $income) or die $DBI::errstr;

print "Want to see employee details(y/n)";


chomp(my $op=<STDIN>);
if($op=='y')
{
print "Employee details are:\n";

my $sth = $dbh->prepare("SELECT FIRST_NAME,


LAST_NAME,GENDER,AGE,INCOME FROM emp1");
$sth->execute() or die $DBI::errstr;
my $i=1;
while (my @row = $sth->fetchrow_array())
{
my ($fn, $ln,$g, $age, $income) = @row;
print "Employee:$i First Name = $fn, Last Name = $ln, GENDER =
$g, AGE = $age, INCOME = $income\n";
$i++
}
$sth->finish();
}

OUTPUT:--

You might also like