You are on page 1of 20

The Perl You Need to Know

Aaron Weiss April 26, 1999 Perl - the very thought evokes a heady, adrenaline rush in the hearts of hard-core hackers, and an intimidating sense of anxiety in practically everyone else. The good news is that you don't need to master Perl to make it useful: Perl is simply a hammer, with which you can build a birdhouse or a mansion. nd you don't need to be !ob "illa to build a birdhouse. #n this article we begin a series on using Perl in web development scenarios. To start, we ease in with a general introduction to Perl itself. $uture articles will take more in-depth looks at #nternet capabilities you can leverage from within Perl programs. This article assumes Perl % as the reference version of Perl. &evelopers who have some familiarity with any other programming language, from ! '#( to Pascal to ( to )ava'cript, will benefit the most from this article* however, readers with no programming background can still follow along and pick up most of the concepts.

"A minute to learn, a lifetime to master" is the slogan for the board game Othello, but it might just as well belong to Perl. Put more accurately, the basic concepts behind Perl are simple to understand, especially for developers familiar with other programming languages. Yet, the open-ended fle ibility of Perl offers seemingly endless possibilities -- which is where the e hilaration and!or intimidation usually sets in. "he good news is that you don't need to master Perl to ma#e it useful. $eb developers ta#e heart% Perl is simply a hammer, with which you can build a birdhouse or a mansion. And you don&t need to be 'ob (illa to build a) birdhouse. *n this article we begin a series on using Perl in web development scenarios. "o start, we ease in with a general introduction to Perl itself. "he purpose of this introduction is not to send you off writing enormous Perl programs -- there are plenty of articles and boo#s which already succeed at this. +ather, this tutorial should arm you with a basic understanding of Perl so that you can wor# through the e amples you care about -- web interaction -- without first needing to become a Perl guru. ,uture articles will ta#e more in-depth loo#s at *nternet capabilities you can leverage from within Perl programs. "his article assumes Perl - as the reference version of Perl, which has supplanted the popular but older Perl . by several years now. /evelopers who have some familiarity with practically any other programming language, from 'A0*1 to Pascal to 1 to 2ava0cript, will benefit the most from this article3 however, readers with no programming bac#ground can still follow along and pic# up most of the concepts by inference.

Contents:
+ho's fraid of Perl, -etting Perl .unning Perl Programs Perl "ariables: 'calars Table /. !asic Perl 0perators Perl "ariables: (omparing 'calars Table 1. Perl (omparison 0perators Perl "ariables: 2ists 3aka rrays4 Perl "ariables: 5ashes Perl $unctions Perl Program $low: (onditionals and 2oops (onclusion

Who's Afraid of Perl?

4any Perl practitioners are 5ealots for the cause -- Perl has evolved into a near-religion for many programmers. "he great advantage of this is that there are many fol#s out there who sincerely believe in the language and wor# hard on its behalf in continued support and development. "he disadvantage of this 5ealotry is a somewhat 6are 7rishna-es8ue style of evangelism which may intimidate many newcomers. Perl "mongers", as they li#e to be #nown, find great pleasure in ma imi5ing their use of this tool, which often comes out in the form of incredibly cryptic Perl programs which pac# e treme amounts of processing into small amounts of code. A typical Perl monger, for e ample, will while away the better portion of a wee#end in a dar#ened room and proudly produce the following gem%

$*=q^00$2b{29}2a;30$17>24&25*2a(1e)1b; 28+1d-26/1b=28+22*1c(1e)17;19@21^, $*.="[1b]28"; $z="";@%=split/\W/,$*;@_=map{hex}@%; for(@_){$_=chr($_+74);s%[zgf]%$z%g;my$t=$_;push@#,sub{$t};} for(@#){print&$_}0xf00f&print$/;


0cary stuff9 $hat does it do: * have no idea9 6owever, this is the #ind of Perl that Perl mongers love to show off as to why Perl is so great. ;nfortunately, well-meaning though they may be, Perl mongers often lac# the ability to empathi5e with normal humans, to whom the above code provides every reason to find a different line of wor#. 0uch as botany. 'eginner&s can ta#e solace -- Perl programs need not be cryptic at all3 in fact, they can be 8uite logical and easy to understand. Although such a style may not leverage the full power of Perl, it does wonders to improve the relationship between Perl and human, and this tutorial will definitely favor legible, clear code over the Perl monger style.

Why Perl and CGI


$eb developers most fre8uently use Perl in the conte t of 1<*. 1<* has been overdescribed to the point of vagary and mystery for many new developers, but the concept is 8uite simple% the user provides some information on the web page and the browser sends this information to the web server. "he web server passes this information to a particular program, this program "does a bunch of stuff" with the information, returns some results to the web server, which passes the results bac# to the user&s browser. 1<*, which translates to "1ommon <ateway *nterface", simply defines the means by which the user&s data passes from the web server to the processing program and bac#. "hat&s basically all you need to #now about the internal guts of 1<*. "he #ey idea to ta#e away from this is that the program which "does a bunch of stuff" with the user&s data can be written in any computer language which runs on the server and can communicate with the server via 1<*. =nter Perl -- Perl can "spea#" 1<* fluently and happens to be well-suited to manipulating data, which is e actly why Perl is the most common language used in developing 1<* interactions. 1<* and Perl are such a powerful combination because, leveraged on the fle ibility of Perl, almost any conceivable type of processing can constitute the "does a bunch of stuff" portion of the 1<* interaction. "hus, when the Perl program receives the user&s data it could follow any number of paths, from retrieving information from a database to constructing and delivering whole new web pages on-the-fly >#nown as "dynamic content"?. 'ut let&s not overwhelm. ,irst we&ll loo# at using Perl to build some simple programs and then we&ll see how to tie these programs into 1<* interactions over the $eb.

Getting Perl
UNIX

Of course, before you can write Perl programs, you&ll need Perl itself. You may already have access to Perl depending on the type of system on which you develop. *f you develop on a ;ni system, such as 0olaris, 0unO0, @inu , any '0/ variant, or the many others, the chances are good that Perl is already installed. You can test this hypothesis 8uite simply -- login to your shell account >usually by telnet? and type%

perl -v
"he output will loo# something li#e%

This is perl, version 5.004_04 built for i386-linux (with 1 registered patch, see perl -V for more detail) Copyright 1987-1998, Larry Wall
As you can see, this sample machine has Perl -.AA.-A. installed. You do want to be sure that your ;B*C system has at least a Perl version of -. 3 the previous version of Perl, .. , may still be installed on many systems. You don&t want to use Perl . because it is old and unfashionable. A number of ;B*C systems have both Perl . and Perl - installed. You may find that "perl" leads to Perl . but the command "perl-" leads to Perl -. "hus, if "perl -v" failed you with a .. version, you might try%

perl5 -v
And see if that reports a -. version of Perl. *f yes, then you should remember that your system refers to Perl - as "perl-" rather than simply "perl" -- this will be necessary to #now later on. *f, for some odd reason, your ;B*C system does not already have Perl installed, you will have to ac8uire Perl and have it installed. "he installation would be done by the system administrator, if that is not yourself. *f that is yourself, you can sometimes obtain ready-made binaries for various ;B*C systems from your vendor >for instance, users of .ed5at 2inux can install the Perl +P4 available on either the +ed6at 1/ or $eb site?. "he brave and courageous can also compile Perl from the source code, available from the Perl.com web site.

WINDOWS
Perl happily runs on other systems besides ;B*C9 *f you develop in $indows, or would li#e to develop Perl programs in both $indows and ;B*C environments, you can easily install the latest version of Perl. Active0tate maintains a $indows version of Perl which is 8uite easy to install, named ctivePerl.

MACOS
/espite its command-line heritage, Perl has even made it ashore on the 4acintosh. Bot that there&s anything wrong with that. A variety of resources for the 4acPerl project can be found the 6acPerl % site.

Running Perl Programs


A Perl program, as we&ll soon see, is a te t file containing Perl code. "here are several ways to launch a Perl program, depending on your needs and the operating system in which you develop.

"ypically, you&ll see that many Perl programs found on the net or in tutorials begin with the line%

#!/usr/bin/perl
"he above line is actually intended for ;B*C systems -- other operating systems will simply ignore it. 6owever, because ;B*C is typically considered the de facto platform for Perl, many Perl programs include this line. *t tells ;B*C where to find the Perl program3 the path /usr/bin/perl is a common location for ;B*C-based Perl installations. *f you are wor#ing in a ;B*C environment, it is important that this first line point to the correct location for Perl on your particular system3 alternatives may loo# li#e, for e ample%

#!/usr/local/bin/perl #!/usr/bin/perl5
*n either ;B*C or $indows, if the perl program is in your search path you can also run a Perl program simply with the command line%

perl programName
$indows users might also use associations to run Perl scripts. $indows associations assign a particular program to run when a filename with a particular e tension is launched. "hus, you can associate the perl e ecutable with filenames ending, for e ample, in .plx or .pl. Active0tate&s Perl installation will setup such an association for you. You can then launch Perl programs by simply double-clic#ing them from the des#top. 7eep in mind that for $eb developers, many Perl programs will be launched in the conte t of 1<*. $e&ll tal# more about 1<* later, but for now you should understand that using Perl programs for 1<* involves a combination of the $eb server&s configuration and the above methods of launching Perl programs.

Show me the Perl: Greetings


A Perl script can be a very simple thing. "he following program does only one thing% outputs the message "$elcome to 1urrency 1entral".

#!/usr/bin/perl print "Welcome to Currency Central\n";


$hat could be simpler: "he only bits in need of e planation here are two% first, note the \n. "he bac#ward slash >)? indicates an escape se8uence, which refers to a special character that cannot easily be typed on the #eyboard. "he \n escape se8uence represents a newline, causing there to be a linefeed in the output following the word "1entral". Also notice the semicolon which represents the end of a Perl statement. Bot all Perl statements re8uire semicolons at the end, but it is good practice, since omitting a semicolon where one is re8uired will definitely result in a program error. *t is always a good idea to add comments to your program code, which ma#e it easy to remember what a particular line does. 0ometimes this is not obvious by simply reading the line of code. 1omments in Perl begin with a pound sign >D?, and continue to the end of that line.

#!/usr/bin/perl #Output welcome message print "Welcome to Currency Central\n";


0imple enough, but this isn&t e actly an impressive display of Perl power. Programming languages derive much of their power from the use of variables. Almost every developer has encountered variables in one scenario or another -- a variable is simply a "container" or label which possesses a certain value. $e begin our study of Perl in earnest with a loo# at variables in Perl.

Perl Variables: !alars


(ariables allow us to manipulate values which, as the name implies, vary over time. (ariables are used to contain values, be they arithmetic >numbers? or strings >a bunch of te t characters?, and variables can be operated upon, meaning added, subtracted, combined, multiplied, and so on. "he most common, basic variable in Perl is #nown as a scalar variable, and is represented by a preceding dollar sign >E?. ,or e ample, imagine that we want to use a variable to #eep the current e change rate between American and 1anadian currency, and this variable will be named "e +ate". *n Perl we would refer to this variable as%

$exRate
$e could simply assign a value to e +ate%

$exRate=1.35;
$e could create another variable, E;0"otal, to represent a dollar amount in American currency, then calculate the value of a resulting variable, E1/B"otal, and output the results.

#!/usr/bin/perl $exRate=1.35; $USTotal=50.00; $CDNTotal=$USTotal*$exRate; print "$USTotal American dollars is equivalent ". "to $CDNTotal Canadian dollars.\n";
"his simple program assigns values to two variables, and in the third line operates on them while assigning the results of that operation to a third variable. "he operator used here is multiplication, represented by the asteris# >F?, a typical operator in programming languages. Botice that the scalar variable names appear within the double-8uoted output string -this may appear unusual to those familiar with other programming languages, but Perl recogni5es that E;0"otal and E1/B"otal are variable names and it substitutes their values in the output. "he resulting output of the above program would loo# li#e%

7ote the way the output strings have been broken up into multiple segments. lthough we could have simply typed one long line, it would have been difficult to read within this article. To make the line more legible, the output string has been broken into portions, with a concatenation operator, the 8.8,between each portion. The result is exactly the same as if we typed one long line.

50 American dollars is equivalent to 67.5 Canadian dollars.


As you can see, a scalar variable holds one "piece" of information, #nown as a value. *n other programming languages, there is strict control over the "types" of data that a value can represent. ,or e ample, a real number is an arithmetic value containing a decimal point >e.g. G-.H-?. An integer is a whole number >e.g. G-?, while a string is a collection of alphanumeric characters >e.g. "hello IJJJ"?. $hereas other languages may demand that you declare the type of value that a variable will contain, Perl is far less strict. *n Perl, you can assign a scalar variable with any type of value you wish -Perl will infer this value&s type using its intelligence. 0oon, we&ll see why this is so useful. $hen using scalar variables, you typically engage in one of two types of actions% operations and comparisons.

Perl Varia les: O!erating on S"alars


$e&ve already seen one e ample of operating on some scalar variables -- recall line K of the previous e ample%

$CDNTotal=$USTotal*$exRate;

"here are two operations here% the multiplication operator, represented by the asteris# >F?, multiplies the value of E;0"otal by the value of Ee +ate. "he assignment operator, represented by the e8ual sign >L?, assigns the result of the multiplication operation to the variable E1/B"otal. +emember previously we opined that Perl uses its intelligence to infer the type of value a variable contains. ,or instance, when you multiply two variables, this operation only ma#es sense if the two variables contain numeric values. You can&t, after all, multiply the value "chic#en" by the value "eggs". "hus, when you use an arithmetic operator, Perl tries its hardest to use the variable&s values as numbers. 0ome operators, though, are not arithmetic. ,or e ample, consider the string concatenation operator, represented by the dot character >.?. 0tring concatenation is the result of s8uishing together two string values3 for instance%

"hello" . "goodbye"

yields

"hellogoodbye"

6ere we come to the important point% if you use an arithmetic operator on two values which can be seen as numbers, Perl will perform the arithmetic. *f you use a string operator on the two values, Perl will treat the values as strings. "hus%

5 + 10 5 . 10

yields yields

15 "510"

Table "# $asi! Perl %&erators


"he table below summari5e the common Perl operators used in arithmetic and string operations.

Table "# $asi! Perl %&erators Operator M F ! Bame addition subtraction /escription 'ums values together. 'ubtracts right value from left value. &ivides left value by right value. .emainder of dividing left value by right value. .aises the left value to the power of the right value. = ample 19:;9 19-/9 19<;9 19>% 19>; 19<<1 8hot8.8dog8 8hot 8.8dog8 %9 /9 =99 ? 1 20 divided by 3 yields 6 (6*3=18) with a re ainder o! 2 (20"18)# ?99 $%&ivalent to 20*20 8hotdog8 8hot dog8 +esult

multiplication 6ultiplies values together. division modulus exponential

FF .

string (hains together the concatenation characters in each value. string replicate .epeats the characters in left value the right value number of times.

8<8x% <<<<< 8<8x%.85ello8.8<8x% <<<<<5ello<<<<<

Perl Variables: 'om&aring !alars


0i5e counts, often, when you must weigh one value against another. +eturning to our currency conversion e ample, you may wish to determine whether the 1anadian dollar figure is a greater or lesser number than its American dollar e8uivalent. $hen you compare two values in Perl, the result is either true or false. ;sing comparison operators you specify the criterion for the comparison. ,or e ample, suppose that E;0"otal contains the value -A and E1/B"otal possesses OH.-. ;sing the arithmetic greaterthan operator >P?%

$USTotal > $CDNTotal $CDNTotal > $USTotal

yields yields

false true

"ypically, you would include one of these comparisons inside a larger e pression, which ma#es use of the result. A simple e ample would be an assignment to a third variable%

$USgreater=($USTotal>$CDNTotal);
*n a later line of code you might test whether E;0greater contained true or false, as a result of the above comparison. 4ore commonly, though, these types of comparisons are used in conditional statements to direct the flow of the Perl program. $e haven&t yet loo#ed at conditional statements, but they should be 8uite familiar to readers with basic programming e perience. Bon-programmers can simply read the e ample aloud to get an idea of the logic behind this code%

if ($USTotal>$CDNTotal) { ...execute some piece of code... } else { ...execute some other piece of code... }

Bow suppose that we wanted to test whether E;0"otal and E1/B"otal were e8ual. ;sing the arithmetic e8uality operator, a double e8ual sign >LL?%

$USTotal == $CDNTotal

yields

false

Of course, if both E;0"otal and E1/B"otal contained the same value, the result of this e8uality comparison would have been true. Programmers note: the arithmetic comparison operator is a double equal sign, not just one. Several other programming languages use a single equal sign to represent both the comparison operator and the assignment operator, and forgetting to use the double equal sign is a common cause of program errors in Perl scripts . +ecall our earlier discussion about data types, and how Perl infers the data type based on the operator being used. *n the above e ample, we are comparing whether one value is greater than another -- this only ma#es sense with numbers, since we cannot say that "dog" is greater than "cat" >well, some might say that, but they would be as#ing for trouble?. *n fact, Perl can ma#e this comparison, but it does so using different logic and different operators. As far as Perl is concerned, "dog" is greater than "cat" because it comes after cat alphabetically. 1onversely, we can say that "cat" is less than "dog". "he string greater-than operator in Perl is "gt", and the string e8uality operator is "e8", thus if EpetA contained "cat" and Epet' contained "dog" we could compare%

$petA gt $petB $petA eq "cat"

yields yields

false true

"here are many possible reasons to compare variables -- this tutorial is not in-depth enough to e plore these in detail. "he table below summari5es the common comparison operators, which you can use when and if you encounter a situation where such a comparison would be useful.

Table (# Perl 'om&arison %&erators


%&erator P Q Name arithmetic greater-than arithmetic )es!ri&tion (ompares whether left value is greater than right value. (ompares whether left value is smaller 19@;9 19A;9 *+am&le false true Result

less-than PL arithmetic greater-than or eBual to arithmetic less-than or eBual to arithmetic eBuality arithmetic ineBuality string greater-than string lessthan string greater-than or eBual to

than right value. (ompares whether left value is eBual to or greater than right value. (ompares whether left value is eBual to or less than right value (ompares whether left value is eBual to right value. (ompares whether left value is not eBual to right value. (ompares whether left value comes alphabetically after right value. (ompares whether left value comes alphabetically before right value. (ompares whether left value is eBual to or comes alphabetically after right value. ;9@C19 true

QL

19AC19

true

LL 9L gt lt

19CC;9 19DC;9 8fat8 gt 8hat8 8fat8 lt 8hat8

false true false true

ge

8pat8 ge 8pat8

true

le

string less(ompares whether left value is eBual to than or eBual or comes alphabetically before right to value. string eBuality string ineBuality (ompares whether left value is exactly the same as the right value. (ompares whether left value is at all different from the right value.

8sat8 le 8pat8

false

e8 ne

8bob8 eB 8bob/8 8bob8 ne 8bob/8

false true

Perl Variables: ,ists -a.a Arra/s0


0o far we&ve been deluged with information on scalar variables, certainly the most commonly used type of variable in Perl >or any other programming language for that matter?. +unner-up in this popularity contest, though, are lists, also commonly #nown as arrays in other languages. @ists, in brief, allow one variable label to contain a bunch of values, rather than merely one.

$e use list variables fre8uently in real life. A shopping list contains a bunch of values -- names of items. A budget is a list of arithmetic values -- e penditures. @ist variables are 8uite different from scalar variables because they do not share the same types of operations. After all, it doesn&t ma#e much sense to compare whether a list of colors is "greater" than a list of pet names >it does ma#e sense to compare whether one list is longer than another, but then the length of a list is a scalar variable?. "o prevent variable name confusion, lists in Perl are prefi ed with the at-sign character >R?. "he values contained in a list are called items, and assigning a list of items to a list is 8uite simple%

@shopping=("milk","eggs","bread","cheetos");
Bow then, the list Rshopping contains four items, inde ed in the order they were created. "he first item in the list is "mil#", the second is "eggs", and so on. 1m&ortant: the first item in a list is counted as index number zero. +estated, item A in this list is "mil#", item I is "eggs", and so on. 6ere&s the confusing bit% when wor#ing with lists, we sometimes wor# with the list as a whole and other times wor# with particular items from the list. $or#ing with a single item from a list is a scalar activity, as we saw in the earlier sections. You can reference a single item from a list using its inde %

$shopping[0]="skim milk";
"he above variable refers to the first item in the Rshopping list, which has been assigned a new value, "s#im mil#". Botice, though, that this reference used a E rather than an R -- because this one item in the list is scalar. $hat if you wanted to wor# with more than one item from the list, but not the whole list: "hat, then, would constitute a slice, because it is still a list >a list of a list9?%

@shopping[0,3]=("skim milk","diet cheetos");


*n this e ample we&ve assigned new values to two of the items in the list, the first and last items. "his time we stuc# with the R prefi , because we have used a slice of the list. *t is 8uite important to use the correct notation, scalar or list, when constructing these references. 0ometimes, using the wrong notion, such as a E where an R should be, won&t result in an error, per se, but in incorrect results within the program. "his is because Perl will interpret the e pression one way or another depending on whether you intended to "see" the variable as a list or a scalar at a given moment. You can determine the length of a list -- that is, how many items it has, using the scalar reference%

$#shopping
"he above returns the number of the highest inde in the list3 in this e ample, that would be K. +emember that the list begins at inde A, so a high inde of K means that this list contains . items. *f you&ve ever wondered why programmers are, well, the way they are ... just remember that they have to deal with this #ind of thing day in and day out9 @ists provide a convenient means for many types of data sorting, but, again, this tutorial is very much a starter course. Once familiar with the basics of these Perl fundamentals, the twists and turns that come down the road will be that much less di55ying.

Perl Variables: 2ashes


"he third and last type of traditional variable that we&ll loo# at in Perl is the hash. 6ashes are conceptually similar to lists in some respects, but offer a different and highly useful e tra functionality.

+ecall our shopping list -- in its original form, this data was suited to a Perl list because it was merely an arbitrary list of items. 'ut would this list be useful in the real world: *f 0usan were to hand her husband 4elvin this list, he might pic# up mil#, but which mil# would he buy: Perhaps 0usan would want 4elvin to purchase the brand of mil# on sale this wee#, meaning that the specific brand to buy may change from wee# to wee#. *n this case, the grocery list must be e panded so that it can relate the items to some additional information3 e.g.

8milk8 is related with 85oly (ow !rand /E8 8eggs8 is related with 8'tore !rand 2arge8 8bread8 is related with 8'murf !akery 2ight +heat8

"he above data, in Perl parlance, is #nown as a set of e!"value pairs. On the left side are the #eys >"mil#","eggs", and "bread"? and on the right side are the values. A hash, then, is actually a list of #ey-value pairs. 6ashes are referred to with the prefi N. 1reating the initial hash for this grocery list is simple%

%shopping=("milk","Holy Cow 1%", "eggs","Store Brand Large", "bread","Smurf Bakery Light Wheat");
As with lists, any single item in the hash is referred to as a scalar variable. ;nli#e lists -- and this is where the power of hashes come in -- the order of the items is unimportant. 6ashes do not use inde es to see their data, they use the #eys. 0o, if we wanted to see the value for the #ey "mil#"%

print $shopping{"milk"};
"he above line would output "6oly 1ow IN". Be t wee#, when the sales change, 0usan can easily assign a different mil# brand value to the mil# #ey%

$shopping{"milk"}="Heffer 2000 Skim";


You can add new #ey-value pairs to the hash at any time using a simple assignment%

$shopping{"dessert"}="HunkaHunka Premium Ice Cream";


6ashes are incredibly useful when you want to create a list but you also want to loo# up data from the list using related bits of data, rather than meaningless inde numbers. Admittedly, most of the people in charge of the wee#ly grocery list don&t manage it using Perl hashes -- but two 8uite practical e amples 8uic#ly spring to mind% I. A translation table. *magine that you are loo#ing up data from a database, and you have used field names to loo# up the data. 0o, the field "+*B(" might represent the "+emaining *nventory" field. $hen you output this data to the screen you might want to reproduce the field labels, but "+*B(" is rather cryptic. *t would be easy to setup a hash that translates the database field names into human-readable field names%

2. %fields("RINV","Remaining 3. Inventory","TINV","Total Inventory"); 4. print "$fields{'RINV'}: $ValueFromDatabase\n";


-. ,re8uency analysis. You are a celebrity linguist designing a word-fre8uency analy5er to help determine how often your own name appears in newspaper articles. =ach uni8ue word counted is entered as the #ey of a hash3 the number of instances of this word is updated as the value of the hash. ,irst, initiali5e an empty hash table%

%freq=();
*magine that Eword represents the most recent word read in from the source data%

$freq{$word}++;
"he above line increments the value of the specified #ey. +e8uesting the fre8uency of the word "happy" then becomes trivially easy%

$freq{"happy"}

Perl 3un!tions

A function is li#e sending out for pi55a ... you call a third-party >the pi55a shop?, provide some parameters >your name, your order?, and in KA minutes or less the results appear at the door. ,unctions, though, wor# much more 8uic#ly and don&t need to be tipped. Perl comes with many, many functions built-in. "hese functions range widely in use, from manipulating numbers and strings to wor#ing with files on dis#. 0ome functions re8uire e tra information to tell them how to do their job -- these are called parameters. 0ome functions are used inside of larger e pressions while others can stand alone. 4any functions can be any of the above. 1onsider the humble lc function. "his function accepts one parameter, a string, and returns a copy of the string in all lowercase letters%

$str="HELLO"; $lowerStr=lc($str);
*n the above, the variable Elower0tr would contain the value "hello". Botice how the lc function is used within an assignment operator3 after all, using lc by itself...

lc($str);
...would not achieve anything since its returned value has nowhere to go and would evaporate. Botice, though, that the lc function does not change the content of Estr at all -- it merely returns a modified cop! of Estr. 0ome functions act directly on the variable passed to them -- these functions happily stand alone. ,or e ample, the chop function hac#s off the last character in a string%

$str="one,two,three,"; chop($str);
"he chop call actually modifies the value of Estr to "one, two,three". Although chop can be used standalone, that doesn&t mean it doesn&t return any information. *n fact, if used in an e pression, chop returns the character that it severed off the original string. "hus%

$str="one,two,three,"; $chopped=chop($str);
"he above would both chop the final comma from Estr and assign that comma to Echopped. "ypically there is no need to save the hac#ed off part of the string, which is why chop is commonly used without being part of a larger e pression. ,unctions don&t necessarily have to accept their parameters inside parentheses. You may well see e amples of functions which are called without any parentheses, such as "chop Estr". *n fact, you&ve already seen such an e ample in this article -- the print function. As a rule of thumb, though, it is best to #eep using the parentheses to enclose parameters being passed to the function -- print is an e ception in that it is widely accepted without parentheses. Perl lets you get away with much syntactical sloppiness, but that doesn&t mean it is a good idea. ;sing functions is straightforward, and an essential part of Perl. "he good news is that Perl includes a huge number of built-in functions ready and waiting to ma#e programming easier, from handling mathematic calculations to hac#ing up strings into various bits and pieces to managing times and dates to writing to and reading from data files. "he bad news is that there are simply too many functions to summari5e in this article. "he e tra good news is that these functions have already been summari5ed and categori5ed, and you can find them in the perlfunc documentation at (P 7, the 1omprehensive Perl Archive Betwor#.

Perl Program 3low: 'onditionals and ,oo&s

'y default, Perl programs, li#e many other languages, e ecute in the order the code is written, from top to bottom. "his order of e ecution is #nown as "program flow" in te tboo#s, and there are a variety of reasons why we might want to alter the program flow under certain circumstances. Again, consider the parallels to real life -- you may plan out your day in a certain order, but variable circumstances may change this order. ,or instance, your day plan might loo# li#e%

if (bank { go to else { go to go to

is open) bank } grocery; bank }

"he use of conditional logic allows your schedule to become more fle ible -- go to the ban# first if it is open, otherwise go to the grocery and then go to the ban#. 0imilarly, we apply the same sort of logic to the flow of Perl programs. "he two main controls which alter program flow are conditionals and loops. 1onditionals, li#e the if...else statement seen in the above e ample, determine what actions to ta#e when certain conditions are met or are not met. @oops are used to repeat one or more actions a certain number of times based upon certain conditions.

i# and $nless statements


One of the most intuitive conditionals is the if statement. You can read this e ample aloud to ma#e the logic perfectly clear%

if (some condition) { ...do some actions when true... }

Botice that the actions clause is enclosed within curly braces. A set of curly braces is #nown as a statement bloc , and any number of Perl statements can appear here, separated by semicolons. +ecalling our currency conversion e ample, we can output a message sensitive to which currency is more valuable than the other%

if ($USTotal>$CDNTotal) { print "Presently, the US dollar is ". "worth more than the Canadian dollar.\n" }
"he else clause of an if statement lets you define a statement bloc# in case the conditional test is false%

if ($USTotal>$CDNTotal) { print "Presently, the US dollar is ". "worth more than the Canadian dollar.\n" } else { print "Presently, the Canadian dollar is ". "worth more than the US dollar.\n" }
;nfortunately, the above e ample is flawed. *t is theoretically possible that both currencies are of e8ual value. "he elsif clause acts as a combined else and if clause, allowing an else clause which tests an additional condition. "his may be clearer by e ample%

7ote the way the output strings have been broken up into multiple segments. lthough we could have simply typed one long line, it would have been difficult to read within this article. To make the line more legible, the output string has been broken into portions, with a concatenation operator, the 8.8, between each portion. The result is exactly the same as if we typed one long line.

if ($USTotal>$CDNTotal) { print "Presently, the US dollar is ". "worth more than the Canadian dollar.\n" } elsif ($USTotal==$CDNTotal) { print "Presently, both the US dollar and ". "the Canadian dollar are of equal value.\n" }

else { print "Presently, the Canadian dollar is ". "worth more than the US dollar.\n" }
"he statement above actually tests two conditions% if the ;0 dollar is worth more then the first message is output3 if the two are e8ual then the second message is output3 the process of elimination tells us that if neither of these were true than the ;0 dollar must be worth less, so the third message it output. A few notes on synta % the formatting and indentation used in these e amples is merely one style, albeit a style this author finds intuitive and legible. Other programmers may favor different styles of indentation -- Perl is very fle ible and essentially lets you format statements and statement bloc#s any way you li#e. Also, note that the elsif clause of this statement is spelled strangely, missing the second "e" that it seems it should have. Perl can be 8uir#y. A related variation of the if statement is the unless statement. "his statement merely tests if the given condition is not true%

unless (bank is open) { go to grocery; go to bank } else { go to bank; go to grocery }


*n this logic, if the ban# is not open then we go shopping first3 otherwise the ban# is open and we go to the ban# first. "he unless statement can sometimes be confusing to wor# through mentally, though it might help to thin# of it as meaning "if the condition is not true". *n every other way unless behaves li#e the if statement, and can ta#e additional elsif and!or else clauses.

while% #or% and #orea"h loo!s


"@ather, rinse, repeat" -- the insightful instructions on the label of shampoo bottles. Yet, this bit of cleansing wisdom sheds light on one of the most fundamental techni8ues in Perl programming -- the loop. *n fact, we can code the shampoo mantra using Perl&s while loop%

while (hairISgreasy) { lather; rinse }


"he shampoo loop starts with a conditional test% is the hair greasy: A statement bloc# follows this test, and this bloc# is e ecuted if the condition is true. "hus, if the hair is greasy, lather and rinse. $hen the statement bloc# is completed, the while loop control returns to the test at the top of the loop. *s the hair greasy: *f yes, the loop iterates again, once more lathering and rinsing. "his loop will iterate ad infinitum until the while condition evaluates to false. *f, on the third iteration, the hair is no longer greasy, the loop ends -- the statement bloc# is not e ecuted and program flow drops to the ne t statement after the while loop&s statement bloc#. *f the while condition is false the first time the loop is evaluated, the statement bloc# is never e ecuted. "he for loop is similar in nature to the while loop but tends to be used when counting is important. A basic e ample would be a for loop which counts from I to IA%

for ($j=1; $j<=10; $j++) { print "$j\n" }


"he for statement ta#es a three-part control%. ,irst, EjLI sets the counting variable for this loop, Ej, to a value of I. You can use any variable name you wish, but Ei and Ej are historically traditional loop counters. "he second part of the for loop&s control is the conditional -- in this case, is Ej less-than or e8ual to the value IA: "he third part of the control advances the counter. 6ere we use the common autoincrement operator which simply adds I to the current value of Ej. "he first time through the loop, Ej contains I, and thus I is output by the print function. "he second time through the loop Ej is incremented to G, is compared against IA, and again is output by the print function. "his process simply repeats until

Ej increments to II, which of course is greater than IA. At that point the loop e its and Perl passes over the statement bloc# and moves onto the ne t statement in the program. $hen dealing with lists, the foreach loop provides a simple way to iterate through each item in the list. +ecall our grocery list from earlier, Rshopping. 0uppose you wanted to wor# with each item in Rshopping%

foreach $shopping_item (@shopping) { do something with $shopping_item }


"his foreach loop does not ta#e any conditional. +ather, it iterates for each item in Rshopping. *n each iteration, the variable EshoppingSitem contains the ne t value in Rshopping. "hus, the first time through the loop EshoppingSitem is "mil#"3 the second time through EshoppingSitem is "bread", and so on. $ithin the statement bloc# of the foreach loop you can modify the value of EshoppingSitem, if need be, without affecting the original value in Rshopping.

Perl Program 3low: 'onditionals and ,oo&s


'y default, Perl programs, li#e many other languages, e ecute in the order the code is written, from top to bottom. "his order of e ecution is #nown as "program flow" in te tboo#s, and there are a variety of reasons why we might want to alter the program flow under certain circumstances. Again, consider the parallels to real life -- you may plan out your day in a certain order, but variable circumstances may change this order. ,or instance, your day plan might loo# li#e%

if (bank { go to else { go to go to

is open) bank } grocery; bank }

"he use of conditional logic allows your schedule to become more fle ible -- go to the ban# first if it is open, otherwise go to the grocery and then go to the ban#. 0imilarly, we apply the same sort of logic to the flow of Perl programs. "he two main controls which alter program flow are conditionals and loops. 1onditionals, li#e the if...else statement seen in the above e ample, determine what actions to ta#e when certain conditions are met or are not met. @oops are used to repeat one or more actions a certain number of times based upon certain conditions.

i# and $nless statements

One of the most intuitive conditionals is the if statement. You can read this e ample aloud to ma#e the logic perfectly clear%

if (some condition) { ...do some actions when true... }

Botice that the actions clause is enclosed within curly braces. A set of curly braces is #nown as a statement bloc , and any number of Perl statements can appear here, separated by semicolons. +ecalling our currency conversion e ample, we can output a message sensitive to which currency is more valuable than the other%

if ($USTotal>$CDNTotal) { print "Presently, the US dollar is ". "worth more than the Canadian dollar.\n" }
"he else clause of an if statement lets you define a statement bloc# in case the conditional test is false%

if ($USTotal>$CDNTotal) { print "Presently, the US dollar is ". "worth more than the Canadian dollar.\n" } else { print "Presently, the Canadian dollar is ". "worth more than the US dollar.\n" }
;nfortunately, the above e ample is flawed. *t is theoretically possible that both currencies are of e8ual value. "he elsif clause acts as a combined else and if clause, allowing an else clause which tests an additional condition. "his may be clearer by e ample%

if ($USTotal>$CDNTotal) { print "Presently, the US dollar is ". "worth more than the Canadian dollar.\n" } elsif ($USTotal==$CDNTotal) { print "Presently, both the US dollar and ". "the Canadian dollar are of equal value.\n" } else { print "Presently, the Canadian dollar is ". "worth more than the US dollar.\n" }

7ote the way the output strings have been broken up into multiple segments. lthough we could have simply typed one long line, it would have been difficult to read within this article. To make the line more legible, the output string has been broken into portions, with a concatenation operator, the 8.8, between each portion. The result is exactly the same as if we typed one long line.

"he statement above actually tests two conditions% if the ;0 dollar is worth more then the first message is output3 if the two are e8ual then the second message is output3 the process of elimination tells us that if neither of these were true than the ;0 dollar must be worth less, so the third message it output. A few notes on synta % the formatting and indentation used in these e amples is merely one style, albeit a style this author finds intuitive and legible. Other programmers may favor different styles of indentation -- Perl is very fle ible and essentially lets you format statements and statement bloc#s any way you li#e. Also, note that the elsif clause of this statement is spelled strangely, missing the second "e" that it seems it should have. Perl can be 8uir#y. A related variation of the if statement is the unless statement. "his statement merely tests if the given condition is not true%

unless (bank is open) { go to grocery; go to bank } else { go to bank; go to grocery }

*n this logic, if the ban# is not open then we go shopping first3 otherwise the ban# is open and we go to the ban# first. "he unless statement can sometimes be confusing to wor# through mentally, though it might help to thin# of it as meaning "if the condition is not true". *n every other way unless behaves li#e the if statement, and can ta#e additional elsif and!or else clauses.

while% #or% and #orea"h loo!s


"@ather, rinse, repeat" -- the insightful instructions on the label of shampoo bottles. Yet, this bit of cleansing wisdom sheds light on one of the most fundamental techni8ues in Perl programming -- the loop. *n fact, we can code the shampoo mantra using Perl&s while loop%

while (hairISgreasy) { lather; rinse }


"he shampoo loop starts with a conditional test% is the hair greasy: A statement bloc# follows this test, and this bloc# is e ecuted if the condition is true. "hus, if the hair is greasy, lather and rinse. $hen the statement bloc# is completed, the while loop control returns to the test at the top of the loop. *s the hair greasy: *f yes, the loop iterates again, once more lathering and rinsing. "his loop will iterate ad infinitum until the while condition evaluates to false. *f, on the third iteration, the hair is no longer greasy, the loop ends -- the statement bloc# is not e ecuted and program flow drops to the ne t statement after the while loop&s statement bloc#. *f the while condition is false the first time the loop is evaluated, the statement bloc# is never e ecuted. "he for loop is similar in nature to the while loop but tends to be used when counting is important. A basic e ample would be a for loop which counts from I to IA%

for ($j=1; $j<=10; $j++) { print "$j\n" }


"he for statement ta#es a three-part control%. ,irst, EjLI sets the counting variable for this loop, Ej, to a value of I. You can use any variable name you wish, but Ei and Ej are historically traditional loop counters. "he second part of the for loop&s control is the conditional -- in this case, is Ej less-than or e8ual to the value IA: "he third part of the control advances the counter. 6ere we use the common autoincrement operator which simply adds I to the current value of Ej. "he first time through the loop, Ej contains I, and thus I is output by the print function. "he second time through the loop Ej is incremented to G, is compared against IA, and again is output by the print function. "his process simply repeats until Ej increments to II, which of course is greater than IA. At that point the loop e its and Perl passes over the statement bloc# and moves onto the ne t statement in the program. $hen dealing with lists, the foreach loop provides a simple way to iterate through each item in the list. +ecall our grocery list from earlier, Rshopping. 0uppose you wanted to wor# with each item in Rshopping%

foreach $shopping_item (@shopping) { do something with $shopping_item }


"his foreach loop does not ta#e any conditional. +ather, it iterates for each item in Rshopping. *n each iteration, the variable EshoppingSitem contains the ne t value in Rshopping. "hus, the first time through the loop EshoppingSitem is "mil#"3 the second time through EshoppingSitem is "bread", and so on. $ithin the statement bloc# of the foreach loop you can modify the value of EshoppingSitem, if need be, without affecting the original value in Rshopping.

'on!lusion
,or many people, the fun of driving a car is not the movement of one&s foot from gas pedal to bra#e pedal, or the method for turning on the wipers or shifting into reverse. "he fun of driving, for most, is the travel -- going from one place to another, the scenery, and of course the speed. 0till, there is a smaller hard-core segment of fol#s who are enamored with shifting gears and how the bra#es wor#. Perl is 8uite the same -- Perl enthusiasts love getting their hands covered with grease, but you can get from A to ' with Perl without needing to #now how to rebuild its transmission9 "his article has tried to survey a wide range of territory towards this end. A web developer is primarily interested in using Perl as a tool towards web-related goals. *n doing so, the web developer will need a basic understanding of the principles of Perl programming, and that has been the focus of much of this introductory piece. ;sing Perl with 1<* to create interactive and dynamic web pages is the fun part of all this. 'ut you can&t cruise the interstate after your first driver&s ed lesson and, similarly, we&ve only seen a glimmer of the fun Perl can offer on the web. "he stage has been set, though, and ne t time we can put this Perl into drive, from validating form submissions to processing database re8uests to shopping cart applications. (room.

Additional &eading '' Some O!inionated (ho$ghts


/espite the perilous pace of technology, there are still some tas#s better done with old fashioned printed boo#s. @earning Perl is one of them. 'oo#s are convenient to reference, are well bound, and easy to carry from bedroom to, er, bathroom. "hat said, if you as# a typical Perl purveyor what boo# to read you&ll undoubtedly be sent the way of ""he @lama", which is an affectionate moni#er for "@earning Perl", by +andal 0chwart5 and "om 1hristiansen, one of the series of O&+eilly and Associates boo#s with strange animal prints on the cover. Allow me to dissent. Although ""he @lama" is the de facto recommendation among the Perl mongers, it is not an ideal boo# with which to begin the Perl journey. A reader who wishes to gain a solid understanding of Perl, coming with little to moderate programming and!or ;ni e perience, one would assert that "@earning Perl" further contributes to the intimidating and cli8uish atmosphere surrounding this powerful and useful language. *n fact, at the ris# of eternal banishment from the Perl 7ingdom 6all and a spate of frighteningly obtuse flame-mails, one would posit that a beginner to Perl would be better served by -- yes -- "Perl - for /ummies", by Paul 6offman. Out on the limb this far, one would go even further to say that the /ummies boo# presents a much clearer organi5ation of Perl information and e plains the essential concepts with far more clarity, and far less ego, than the e alted @lama. *n self-defense, it should be noted that the authors of "@earning Perl", 4r. 0chwart5 and 4r. 1hristiansen most certainly #now their stuff -- they are true high priests of Perl. "heir writings provide great insight into the wor#ings of Perl and into its advanced usage, and are highly recommended for those at such a level of interest. 0imply put, though, a newcomer to the language will gain a more useful understanding from the clarity and structure of "Perl - for /ummies". And it should be noted that there are no invested ties to either of these opinions. "his is no indictment of all animal-print covers -- in fact, one does recommend that any level of Perl programmer would benefit from O&+eilly&s "Perl in a Butshell", by =llen 0iever, 0tephen 0painhour, and Bathan Patwardhan >featuring a camel head cover?. Although it contains little instruction or narrative, this boo# is an e cellent reference resource summari5ing all aspects of the Perl language, from operators to functions to the many popular modules.

&eso$r"es

The Perl &ocumentation >thorough9?

'elena 'ol's #ntroduction to Perl (-# Programming /9/, by )acBueline &. 5amilton (-# 6odule .eference >technical? 'ummary and &ocumentation of 'tandard Perl 6odules

You might also like