Introduction To Perl:: #!c:/xampp/perl/bin/perl - Exe
Introduction To Perl:: #!c:/xampp/perl/bin/perl - Exe
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.
#!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!";
$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
output:---
David paid $4.34 for Larry's shirt.
youremail@youremail.com
$string and $email
definescalars.pl:
#!/usr/bin/perl
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.
definearrays.pl:
#!/usr/bin/perl
Display:
MondayTuesdayWednesday
AprilMayJune
definehashes.pl:
print "Content-type: text/html \n\n"; #HTTP HEADER
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
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
# STRINGS TO BE FORMATTED
$mystring = "welcome to tizag.com!"; #String to be formatted
$newline = "welcome to \ntizag.com!";
$capital = "\uwelcome to tizag.com!";
$ALLCAPS = "\Uwelcome to tizag.com!";
Any combination of these special characters can be used at any time to properly punctuate your strings. They also come in handy when
printing out HTML with your PERL functions.
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
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
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!
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
perltrig.pl:
-3.27370380042812
2.65358979335273e-06
3.14159265358979-2.06343706889556i
arithmeticoperations.pl:
#!/usr/bin/perl
arithmeticoperations.pl:
140
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
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).
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
arithmetic.pl:
81 plus 9 is 90
81 minus 9 is 72
81 times 10 is 810
81 divided by 9 is 9
81 to the 5th is 3486784401
81 modulus 79 is 2
Assignment Operators:
Operator Definition Example
+= Addition ($x += 10)
-= Subtraction ($x -= 10)
*= Multiplication ($x *= 10)
/= Division ($x /= 10)
%= Modulus ($x %= 10)
**= Exponent ($x **= 10)
PERL Assignment:
#!/usr/bin/perl
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.
Logical operators state and/or relationships. Meaning, you can take two variables and test an either or conditional. Logical operators are
used later on in conditionals and loops. For now, just be able to recognize them in the upcoming examples.
Logical/Relational Operators:
Relational
Operator Example Defined Result
5 == 5
==,eq Test: Is 5 equal to 5? True
5 eq 5
7 != 2
!=,ne Test: Is 7 not equal to 2? True
7 ne 2
7<4
<,lt Test: Is 7 less than 4? False
7 lt 4
7>4
>,gt Test: Is 7 greater than 4? True
7 gt 4
7 <= 11
<=,le Test: Is 7 less than or equal to 11? True
7 le 11
7 >= 11
>=,ge Test: Is 7 greater than or equal to 11? False
7 ge 11
Logical
Operator Defined Example
&&,and Associates two variables using AND if (($x && $y) == 5)...
||,or Associates two variables using OR if (($x || $y) == 5)...
Please note that you must use each different operator depending of whether or not you are comparing strings or numbers. In the table
above, the black operators are for numbers and the red ones are for strings.
PERL Code:
#!/usr/bin/perl
print $string3;
Display:
Hello, World
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!
perl - if else
The else statement is a perfect compliment to an if statement. The idea behind them is that if the conditional statement is not met then
do this. In hypothetical, plain english, "If this is true do this, if not do this."
ifelse.pl:
#!/usr/bin/perl
# HTTP HEADER
print "content-type: text/html \n\n";
# SOME VARIABLES
$name = "Sarah";
$x = 5;
# IF/ELSE STATEMENTS
if ($x > 10) {
print "$x is greater than 10!";
} else {
print "$x is not greater than 10!";
}
print "<br />";
elsif.pl:
#!/usr/bin/perl
# HTTP HEADER
print "content-type: text/html \n\n";
# SOME VARIABLES
$x = 5;
We could take this example a step further, adding an else statement at the bottom. This would serve as a catch all if none of the
conditions were met.
orloop.pl:
#!/usr/bin/perl
# 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.
foreachloop.pl:
#!/usr/bin/perl
# CREATE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
foreachloop.pl:
1 Steve
2 Bill
3 Connor
4 Bradley
We placed a table row counter for you to see each line more clearly. We use the variable $names to pull single elements from our array,
PERL does the rest for us by looping through each element in our array. Use the sorting functions outlined in the PERL Arrays lesson.
perl - while
While loops continually 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
# SET A VARIABLE
$count = 0;
whilecounter.pl:
0
1
2
3
4
5
6
7
Finished Counting!
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
# SET A VARIABLE
$count = 0;
while ($count <= 7) {
}
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.
whilearrayloop.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@names = qw(Steve Bill Connor Bradley);
while.pl:
1 Steve
2 Bill
3 Connor
4 Bradley
perl - hashes
Hashes are complex list data, like arrays except they link a key to a value. To define a hash, we use the percent (%) symbol before the
name.
defineahash.pl:
#!/usr/bin/perl
print "content-type: text/html \n\n";
# DEFINE A HASH
%coins = ("Quarter", 25, "Dime", 10, "Nickel", 5);
Display:
Nickel5Dime10Quarter25
legiblehash.pl:
#!/usr/bin/perl
# DEFINE A HASH
%coins = ( "Quarter" , 25,
"Dime" , 10,
"Nickel", 5 );
# LOOP THROUGH IT
while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
}
legiblehash.pl:
Nickel, 5
Dime, 10
Quarter, 25
The each() function 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.
tablehashes.pl:
#!/usr/bin/perl
# DEFINE A HASH
%coins = ( "Quarter" , 25,
"Dime" , 10,
"Nickel", 5 );
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.
sortkeys.pl:
#!/usr/bin/perl
# DEFINE A HASH
%coins = ( "Quarter" , 25,
"Dime" , 10,
"Nickel", 5 );
# FOREACH LOOP
foreach $key (sort keys %coins) {
print "$key: $coins{$key}<br />";
}
sortkeys.pl:
Dime: 10
Nickel: 5
Quarter: 25
The $coins($key) represents the variable assigned by PERL to each value of each element. Use this short cut to quickly retrieve each
value element from your hashes.
We need to edit our hash to and change is the values to floating-point numbers. This way PERL will properly sort our hash by our values
as the nickel element will be valued according to a value of "05" instead of "5".
sortvalues.pl:
#!/usr/bin/perl
# DEFINE A HASH
%coins = ( "Quarter" , .25,
"Dime" , .10,
"Nickel", .05 );
# FOREACH LOOP
foreach $value (sort {$coins{$a} cmp $coins{$b} }
keys %coins)
{
print "$value $coins{$value}<br />";
}
sortvalues.pl:
Nickel 0.05
Dime 0.1
Quarter 0.25
perl - add an element
Adding a new key/value pair can be done with one line of code. This example is straight forward, we add the key/value pairs of penny/01
and half dollar/50 to the existing hash.
addelements.pl:
#!/usr/bin/perl
# BEGINNING HASH
%coins = ( "Quarter" , .25,
"Dime" , .10,
"Nickel", .05 );
# PRINT THE OLD HASH
while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
}
addelements.pl:
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.
removeelements.pl:
#!/usr/bin/perl
# DEFINED HASH
%coins = ( "Quarter" , .25,
"HalfDollar" , .50,
"Penny" , .01,
"Dime" , .10,
"Nickel", .05 );
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 Code:
#!/usr/bin/perl
PERL Code:
#!/usr/bin/perl
$filepath = "myhtml.html";
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
$FH = "filehandle";
$FilePath = "myhtml.html";
Files with special characters or unusual names are best opened by first declaring the URL as a variable. This method removes any
confusion that might occur as PERL tries to interpret the code. Tildas in filenames however require a brief character substitution step before
they can be placed into your open statements.
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
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
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:
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 Code:
#!/usr/bin/perl
myhtml.pl:
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 Code:
#!/usr/bin/perl
dynamic.pl:
Dynamic Table
Temporarily Inserted Using PERL!
To permanently change a file, replace the print function with the printf function.
PERL Code:
#!/usr/bin/perl
use File::Copy;
Here, we have simply duplicated the "myhtml.html" file and will be using it in further examples.
If we wanted to copy the file to a new directory, we can edit our variables to match the directory we wish to copy the file to.
PERL Code:
#!/usr/bin/perl
use File::Copy;
Now we have copied the file from its current directory to an HTML directory.
When using PERL on the web, it is best to use complete internet URL. We used a shorthand way in the example but a better solution
may be to hardcode the full URL meaning; http://www.your.com/myhtml.html.
PERL Code:
#!/usr/bin/perl
use File::Copy;
PERL Code:
#!/usr/bin/perl
deletefiles.pl:
File deleted successfully.
PERL Code:
#!/usr/bin/perl
perlarrays.pl:
#!/usr/bin/perl
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.
arrayindexing.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");
arrayindexing.pl:
Quarter Dime Nickel
Quarter
Dime
Nickel
Elements can also be indexed backwards using negative integers instead of positive numbers.
arrayindexing2.pl:
#!/usr/bin/perl
# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");
arrayindexing2.pl:
Quarter Dime Nickel
Quarter
Nickel
Dime
PERL Code:
#!/usr/bin/perl
Display:
Quarter Dime Nickel
sequentialarrays.pl:
#!/usr/bin/perl
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
@nums = (1 .. 20);
@alpha = ("a" .. "z");
# SCALAR FUNCTION
print scalar(@nums)."<br />";
print scalar(@alpha)."<br />";
# REDEFINE TO SCALAR
$nums = @nums;
$alpha = @alpha;
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.
When adding elements using push() or shift() you must specify two arguments, first the array name and second the name of the element
to add. Removing an element with pop() or shift() only requires that you send the array as an argument.
modifyarrays.pl:
#!/usr/bin/perl
# AN ARRAY
@coins = ("Quarter","Dime","Nickel");
# ADD ELEMENTS
push(@coins, "Penny");
print "@coins";
print "<br />";
unshift(@coins, "Dollar");
print "@coins";
# REMOVE ELEMENTS
pop(@coins);
print "<br />";
print "@coins";
shift(@coins);
print "<br />";
modifyarrays.pl:
Quarter Dime Nickel Our original Array, 3 elements.
Quarter Dime Nickel Penny Add penny to the end.
Dollar Quarter Dime Nickel Penny Add Dollar to the beginning.
Dollar Quarter Dime Nickel Remove Penny.
Quarter Dime Nickel Remove dollar, back to the original!
Array Functions:
Function Definition
push(@array, Element) Adds to the end of an array
pop(@array) Removes the last element of the array
unshift(@array, Element) Adds to the beginning of an array
shift(@array) Removes the first element of an array
delete $array[index] Removes an element by index number
It is also possible to remove any element by its indexed number. Just remember to use the scalar form of the array when doing so.($)
slicendice.pl:
#!/usr/bin/perl
When handling lists of sequential numbers, the range operator can quickly become your favorite tool for slicing up arrays.
myrangefriend.pl:
#!/usr/bin/perl
# SEQUENTIAL ARRAY
@nums = (1..200);
@slicenums = @nums[10..20,50..60,190..200];
print "@slicenums";
myrangefriend.pl:
11 12 13 14 15 16 17 18 19 20 21 51 52 53 54 55 56 57
58 59 60 61 191 192 193 194 195 196 197 198 199 200
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
@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."
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";
split.pl:
Rain Drops On Roses And Whiskers On Kittens
Larry David Roger Ken Michael Tom
Notice you have to send the split function where the split will occur. In the first example, the split was called at each hyphen. In the latter
example the names were split by a comma, allowing for the split to take place between each name.
Likewise, we can use the join() function to rejoin the array elements and form one long, scalar string.
arraytostring.pl:
#!/usr/bin/perl
# A COUPLE OF ARRAYS
@array = ("David","Larry","Roger","Ken","Michael","Tom");
@array2 = qw(Pizza Steak Chicken Burgers);
join.pl:
David,Larry,Roger,Ken,Michael,Tom
Pizza Steak Chicken Burgers
The characters specified in our join() argument are the characters used in between each element of the array. This allows us to format
the new strings with blank spaces between each word. We could replace the blank spaces with any characters including HTML Elements
such as a line break tag.
stringformatting.pl:
#!/usr/bin/perl
print "$string";
stringformatting.pl:
Pizza
Steak
Chicken
Burgers
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
# TWO ARRAYS
@foods = qw(pizza steak chicken burgers);
@Foods = qw(Pizza Steak chicken burgers);
# SORT 'EM
@foods = sort(@foods);
@Foods = sort(@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
# TRANSFORM TO LOWERCASE
foreach $food (@Foods) {
push(@foods, "\L$food");
}
# SORT
@foods = sort(@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.
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";
hickory
dickory
doc
Again, let's check the same example without using $_ variable explicitly −
#!/usr/bin/perl
foreach ('hickory','dickory','doc') {
print;
print "\n";
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.
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.
$ARG
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.
sub subroutine_name{
body of the subroutine
}
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.
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();
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;
# Function call
Average(10, 20, 30);
#!/usr/bin/perl
# Function definition
sub PrintList{
my @list = @_;
print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
Given list is 10 1 2 3 4
#!/usr/bin/perl
# Function definition
sub PrintHash{
my (%hash) = @_;
name : Tom
age : 19
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;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";
sub somefunc {
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";
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";
Let's check the following example to demonstrate the use of state variables
−
#!/usr/bin/perl
sub PrintCount{
state $count = 0; # initial value
for (1..5){
PrintCount();
}
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
#!/usr/bin/perl
{
my $count = 0; # initial value
sub PrintCount {
print "Value of counter is $count\n";
$count++;
}
}
for (1..5){
PrintCount();
}
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.
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.
This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
#!/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";
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.
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.
If everything goes fine then commit this operation otherwise you can rollback complete transaction.
Commit and Rollback are explained in next sections.
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.
$age = 20;
FROM TEST_TABLE
$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.
$sth->finish();
$sex = 'M';
$sth->finish();
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;
SET INCOME = ?
$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.
If everything goes fine then commit this operation otherwise you can rollback complete transaction.
$age = 30;
$sth->finish();
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.
perlmysqlconfig.pl:
#!/usr/bin/perl
perlmysqlconnect.pl:
#!/usr/bin/perl
# PERL MODULE
use Mysql;
# HTTP HEADER
print "Content-type: text/html \n\n";
# CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";
If this script was run on your web server through a web browser, you should be starring at a blank white screen and all is well.
listdbs.pl:
@databases = $connect->listdbs;
We can then loop through this array and print out our results to the browser.
listdbs2.pl:
#!/usr/bin/perl
# PERL MODULES
use Mysql;
# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);
# LISTDBS()
@databases = $connect->listdbs;
foreach $database (@databases) {
print "$database<br />";
}
perlmysqlselectdb.pl:
#!/usr/bin/perl
# PERL MODULE
use Mysql;
# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);
# SELECT DB
$connect->selectdb($database);
Notice how the syntax requires that we connect to our host each time we perform a function. You will see this with nearly every script we
execute. Once we are connected, the sky is the limit as to what queries we can execute.
listtables.pl:
#!/usr/bin/perl
use Mysql;
# HTTP HEADER
print "Content-type: text/html \n\n";
# SELECT DB
$connect->selectdb($database);
# LISTTABLES()
@tables = $connect->listtables;
The database is defined when we run the $connect variable. To change the script to a different database simply run a new selectdb()
function or change the $database variable.
perlinsertquery.pl:
#!/usr/bin/perl
use Mysql;
# SELECT DB
$connect->selectdb($database);
# AFFECTED ROWS
$affectedrows = $execute->affectedrows($myquery);
# ID OF LAST INSERT
$lastid = $execute->insertid($myquery);
These functions could be run without defining them as scalar variables as well.
easyselectfunctions.pl:
#!/usr/bin/perl
use Mysql;
# HTTP HEADER
print "Content-type: text/html \n\n";
# SELECT DB
$connect->selectdb($database);
$rownumber = $execute->numrows();
$fieldnumber = $execute->numfields();
fetchrow.pl:
#!/usr/bin/perl
use Mysql;
# SELECT DB
$connect->selectdb($database);
# HTML TABLE
print "<table border='1'><tr>
<th>id</th>
<th>product</th>
<th>quantity</th></tr>";
# FETCHROW ARRAY
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.
#!/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 '</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 −
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.
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.
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.
#!/usr/bin/perl
1;
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:
#!/usr/bin/perl
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.
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:
Select Subject
Maths Physics
#!/usr/bin/perl
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;
Select Subject
Maths Physics
#!/usr/bin/perl
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;
Submit
Below is the textarea.cgi script to handle input given by the web browser.
#!/usr/bin/perl
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;
Maths Submit
#!/usr/bin/perl
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;
}
$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
print;
}
OUTPUT:--
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
$str=$user.":".$password ;
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>);
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;
$sth->execute();
{
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>);
OUTPUT:--