Perl 5 Tutorial
First Edition
Chan Bernard Ki Hong
Perl is copyright by Larry Wall. Linux is a trademark of Linus Torvalds. Torvalds. Unix is a trademark of AT&T AT&T Bell Laboratories.
Perl 5 Tutorial First Edition Author: Chan Bernard Ki Hong (
[email protected]) Web site: http://www.cbkihong.com Date of Printing: December 24, 2003 Total Number of Pages: 241 Prepared from LATEX source files by the author.
© 2001–2003 by Chan Bernard Ki Hong.
While the author of this document has taken the best effort in enhancing the technical accuracy as well as readability of this publication, please note that this document is released “as is” without guarantee for accuracy or suitability of any kind. The full text of the terms and conditions of usage and distribution can be found at the end of this document. In order to further enhance the quality of this publication, the author would like to hear from you, the fellow readers. Comments or suggestions on this publication are very much appreciated. Please feel free to forward me your comments through the email feedback form or the feedback forum on the author’s Web site.
Contents 1
2
3
Introduction Introductio n to Pro Programm gramming ing 1.1 Wh What at is Pe Perl? rl? . . . . . . . . . . . . . . . . . . . . 1.2 A Trivial Introduction to Computer Programming 1.3 Scr Script iptss vs. Pr Progr ograms ams . . . . . . . . . . . . . . . . 1.4 An Overview Overview of the the Softwar Softwaree Develop Development ment Pro Proces cesss Getting Getti ng Sta Starte rted d 2.1 Wh What at can Perl do? . . . . . . . . . . . . . . . . . . 2.2 Comp Compariso arison n with with Other Other Pro Programm gramming ing Langu Languages ages 2.2. 2. 2.1 1 C/C /C++ ++ . . . . . . . . . . . . . . . . . . . 2.2.2 PHP . . . . . . . . . . . . . . . . . . . . . 2.2. 2. 2.3 3 Jav ava/ a/JS JSP P. . . . . . . . . . . . . . . . . . . 2.2.4 ASP . . . . . . . . . . . . . . . . . . . . . 2.3 What do I need to learn Pe Perl? rl? . . . . . . . . . . . . 2.4 Mak Makee Good Good Us Usee of of Online Online Res Resour ources ces . . . . . . . . 2.5 The Traditional “Hello World” Program . . . . . . 2.6 How A Perl Perl Pro Program gram Is Exe Execute cuted d . . . . . . . . . . 2.7 2. 7 Li Lite tera rals ls . . . . . . . . . . . . . . . . . . . . . . . 2.7. 2. 7.1 1 Num umbe bers rs . . . . . . . . . . . . . . . . . . 2.7. 2. 7.2 2 St Stri ring ngss . . . . . . . . . . . . . . . . . . . 2.8 Intr Introduct oduction ion to Data Struc Structur tures es . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
Manipula Manip ulatio tion n of Dat Dataa Str Struct ucture uress 3.1 Sca Scalar lar Vari ariabl ables es . . . . . . . . . . . . . . . . . . . . . . . . . 3.1. 3. 1.1 1 As Assi signm gnmen entt . . . . . . . . . . . . . . . . . . . . . . . 3.1.2 3.1 .2 Nome omencl nclatu ature re . . . . . . . . . . . . . . . . . . . . . 3.1.3 Variabl ariablee Sub Substit stitution ution . . . . . . . . . . . . . . . . . . 3.1.4 substr() — Extraction of Substrings . . . . . . . . 3.1.5 length() — Length of String . . . . . . . . . . . . . 3.2 Lis Lists ts and Ar Array rayss . . . . . . . . . . . . . . . . . . . . . . . . . 3.2.1 3.2 .1 Cr Creat eating ing an Arr Array ay . . . . . . . . . . . . . . . . . . . 3.2.2 3.2 .2 Ad Addin dingg Ele Elemen ments ts . . . . . . . . . . . . . . . . . . . . 3.2.3 Gett Getting ing the numb number er of Elem Elements ents in an Array Array . . . . . 3.2.4 Ac Acces cessing sing Elem Elements ents in an Arra Array y . . . . . . . . . . . . 3.2.5 3.2 .5 Re Remo moving ving Ele Eleme ments nts . . . . . . . . . . . . . . . . . . 3.2.6 splice(): the Versatile Versatile Function . . . . . . . . . . . 3.2.7 Mis Miscell cellaneou aneouss List List-Rel -Related ated Func Functions tions . . . . . . . . . 3.2.8 Chec Check k for for Exist Existence ence of Element Elementss in an Array Array (A (Avoid void!) !) 3.3 3. 3 Ha Hash shes es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3. 3. 3.1 1 As Assi signm gnmen entt . . . . . . . . . . . . . . . . . . . . . . . i
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . .
1 1 1 3 4
. . . . . . . . . . . . . .
7 7 8 8 8 9 9 9 11 12 15 16 16 16 17
. . . . . . . . . . . . . . . . .
23 23 23 24 25 26 26 26 27 28 29 30 31 32 33 35 38 38
ii
CONTE ONTEN NTS
3.4 3.4 3.5 4
5
6
3.3.2 Ac Acces cessing sing elem elements ents in the Hash . . 3.3.3 Rem Removing oving Elem Elements ents fro from m a Hash . 3.3.4 Sear Searchin chingg for an Elem Element ent in a Hash Cont Co ntex exts ts . . . . . . . . . . . . . . . . . . . Miscellane Misc ellaneous ous Iss Issues ues with List Listss . . . . . . .
Operat Oper ator orss 4.1 Int Intro roduc ductio tion n . . . . . . . . . . . . . . . 4.2 Desc Descripti ription on of some Oper Operator atorss . . . . . . 4.2.1 4.2 .1 Ar Arith ithmet metic ic Ope Operat rator orss . . . . . . 4.2.2 Strin Stringg Manip Manipulati ulation on Opera Operator torss . 4.2.3 4.2 .3 Co Compa mparis rison on Ope Operat rator orss . . . . . 4.2.4 4.2 .4 Equ Equali ality ty Ope Operat rator orss . . . . . . . . 4.2.5 4.2 .5 Log Logica icall Ope Operat rators ors . . . . . . . . 4.2.6 4.2 .6 Bi Bitwi twise se Ope Operat rators ors . . . . . . . . 4.2.7 4.2 .7 As Assi signm gnment ent Ope Operat rators ors . . . . . . 4.2.8 4.2 .8 Oth Other er Ope Operat rator orss . . . . . . . . . 4.3 Opera Operator tor Pre Precede cedence nce and Ass Associat ociativity ivity . . 4.4 Cons Construct tructing ing Your Own sort() Routine
. . . . . . . . . . . .
. . . . .
. . . . . . . . . . . .
. . . . .
. . . . . . . . . . . .
. . . . .
. . . . . . . . . . . .
Conditio Condi tional nals, s, Loo Loops ps & Sub Subro routi utines nes 5.1 Bre Breaking aking Up Your Code . . . . . . . . . . . . . . 5.1.1 Sour Sourcing cing Exte External rnal Files with require() 5.2 Sc Scope ope and Cod Codee Blo Blocks cks . . . . . . . . . . . . . . 5.2.1 Intr Introduc oduction tion to Ass Associat ociations ions . . . . . . . 5.2. 5. 2.2 2 Co Code de Bl Bloc ocks ks . . . . . . . . . . . . . . . 5.3 Su Subr brout outine iness . . . . . . . . . . . . . . . . . . . . 5.3.1 Cre Creating ating and Us Using ing A Sub Subrou routine tine . . . . 5.3. 5. 3.2 2 Pr Prot otot otype ypess . . . . . . . . . . . . . . . . 5.3. 5. 3.3 3 Re Recu curs rsio ion n. . . . . . . . . . . . . . . . . 5.3.4 Cre Creating ating Cont Contextext-sens sensitiv itivee Sub Subrou routines tines . 5.4 5. 4 Pa Pack ckag ages es . . . . . . . . . . . . . . . . . . . . . . 5.4.1 5.4 .1 De Decla clarin ringg a Pa Packa ckage ge . . . . . . . . . . . 5.4.2 Pac Package kage Variabl ariablee Ref Refere erencing ncing . . . . . . 5.4.3 Pac Package kage Variabl ariables es and Sym Symbol bol Tables . . 5.4.4 Pac Package kage Cons Construct tructors ors with BEGIN {} . . 5.5 Lexi Lexical cal Bind Binding ing and Dynam Dynamic ic Bind Binding ing . . . . . . 5.6 Con Condit dition ionals als . . . . . . . . . . . . . . . . . . . 5.7 5. 7 Lo Loo ops . . . . . . . . . . . . . . . . . . . . . . . 5.7.1 for loop . . . . . . . . . . . . . . . . . 5.7.2 while loop . . . . . . . . . . . . . . . . 5.7.3 foreach loop . . . . . . . . . . . . . . 5.7.4 Loop Contr Control ol Stat Statemen ements ts . . . . . . . . 5.8 5. 8 Le Left ftov over erss . . . . . . . . . . . . . . . . . . . . . Ref efer eren ence cess 6.1 Int Intro roduc ductio tion n . . . . . . . . . 6.2 Cre Creating ating a Ref Refere erence nce . . . . . 6.3 Us Using ing Ref Refere erences nces . . . . . . . 6.4 Pa Pass ss By Re Refe fere rence nce . . . . . . . 6.5 How Ev Everything erything Fits Toget ogether her
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . .
. . . . .
40 40 41 42 44
. . . . . . . . . . . .
47 47 48 48 50 51 53 54 56 57 58 59 64
. . . . . . . . . . . . . . . . . . . . . . .
67 67 67 69 69 69 70 71 73 75 78 80 80 81 81 82 82 86 88 88 89 89 91 91
. . . . .
95 95 95 97 100 101
CON CONTEN TENTS 6.6 6. 6 7
8
9
iii
Type ypegl glob obss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Object-Orient Object-Ori ented ed Pro Programm gramming ing 7.1 Int Intro roduc ductio tion n . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2 Object Object-Orie -Oriented nted Conc Concepts epts . . . . . . . . . . . . . . . . . . . . . 7.2.1 7.2 .1 Pr Progr ogramm amming ing Pa Parad radigm igmss . . . . . . . . . . . . . . . . . 7.2. 7. 2.2 2 Ba Basi sicc Id Idea eass . . . . . . . . . . . . . . . . . . . . . . . . . 7.2.3 Fund Fundament amental al Elem Elements ents of Objec Object-Ori t-Oriente ented d Program Programming ming 7.3 OOP Pri Primer mer:: Sta Statis tistic ticss . . . . . . . . . . . . . . . . . . . . . . . 7.3.1 Cre Creating ating and Us Using ing A Pe Perl rl Class . . . . . . . . . . . . . . 7.3.2 Ho How w A Clas Classs Is Inst Instantiat antiated ed . . . . . . . . . . . . . . . . 7.4 7. 4 In Inhe heri rita tanc ncee . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
Files and Fil Files Fileha ehandl ndles es 8.1 Int Intro roduc ductio tion n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 8. 2 Fi File leha hand ndle less . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2.1 open a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2.2 8.2 .2 Out Output put Re Redir direct ection ion . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 File Input and Outp Output ut Func Functions tions . . . . . . . . . . . . . . . . . . . . . . . 8.3.1 readline() — Read A Line from Filehandle . . . . . . . . . . . . 8.3.2 binmode() — Binary Mode Declaration . . . . . . . . . . . . . . 8.3.3 read() — Read A Specified Number of Characters from Filehandle 8.3.4 print()/printf() — Output To A FileHandle . . . . . . . . . . 8.3.5 seek() — Set File Pointer Position Position . . . . . . . . . . . . . . . . . 8.3.6 tell() — Return File Pointer Position Position . . . . . . . . . . . . . . . 8.3.7 close() — Close An opened File . . . . . . . . . . . . . . . . . . 8.4 Dir Directo ectory ry Trav raversa ersall Func Functions tions . . . . . . . . . . . . . . . . . . . . . . . . 8.4.1 opendir() — Open A Directory . . . . . . . . . . . . . . . . . . 8.4.2 readdir() — Read Directory Content . . . . . . . . . . . . . . . 8.4.3 closedir() — Close A Directory . . . . . . . . . . . . . . . . . . 8.4.4 8.4 .4 Exa Examp mple: le: Fil Filee Sea Searc rch h . . . . . . . . . . . . . . . . . . . . . . . . . 8.5 File Test Opera Operator torss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.6 8. 6 Fi File le Lo Lock ckin ingg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Regular Expr Regular Expressio essions ns 9.1 Int Intro roduc ductio tion n . . . . . . . . . . . . . . . . . . . . . . 9.2 Bu Build ilding ing a Pa Patt ttern ern . . . . . . . . . . . . . . . . . . . . 9.2.1 Gett Getting ing you yourr Foo Foott Wet . . . . . . . . . . . . . 9.2.2 9.2 .2 Int Intro roduc ductio tion n to m// and the Binding Operator 9.2.3 9.2 .3 Me Metac tachar haract acter erss . . . . . . . . . . . . . . . . . 9.2. 9. 2.4 4 Qu Quant antifi ifier erss . . . . . . . . . . . . . . . . . . . 9.2.5 9.2 .5 Cha Charac racte terr Cla Class sses es . . . . . . . . . . . . . . . . 9.2. 9. 2.6 6 Ba Back cktr trac acki king ng . . . . . . . . . . . . . . . . . . 9.3 Reg Regular ular Expr Express ession ion Opera Operator torss . . . . . . . . . . . . . 9.3.1 m// — Pattern Matching . . . . . . . . . . . . 9.3.2 s/// — Search and Replace . . . . . . . . . . 9.3.3 tr/// — Global Character Transliteration . . 9.4 Cons Construct tructing ing Com Complex plex Reg Regular ular Expr Express essions ions . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . .
105 105 105 105 106 107 107 110 111 113
. . . . . . . . . . . . . . . . . . .
119 119 119 120 121 122 122 122 123 124 126 127 127 128 128 128 128 128 131 132
. . . . . . . . . . . . .
137 137 138 138 139 139 141 141 142 143 143 144 144 145
iv
CON CONTEN TENTS
10 Runtime Runtime Eva Evaluatio luation n & Error Error Trappin rapping g 10.1 Warnings and Exceptions Exceptions . . . . . . . . . . . . . 10.2 Error Error-Related -Related Functions . . . . . . . . . . . . . 10.3 eval . . . . . . . . . . . . . . . . . . . . . . . . 10.4 Backt Backticks icks and system() . . . . . . . . . . . . . 10.5 Why Runtime Evaluation Should Be Restricted Restricted . 10.6 Next Generation Exception Exception Handling . . . . . . 10.6.1 10.6. 1 Basi Basicc Ide Ideas as . . . . . . . . . . . . . . . . 10.6.2 Throwing Different Kinds of Errors . . . 10.6.3 10.6. 3 Othe Otherr Handl Handlers ers . . . . . . . . . . . . . . 10.7 Other Methods Methods To To Catch Programming Errors . 10.7 10 .7.1 .1 Th Thee -w Switch — Enable Warnings . . . 10.7.2 Banning Uns Unsafe afe Constructs With strict 10.7 10 .7.3 .3 Th Thee -T Switch — Enable Taint Checking
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
11 CGI Pro Programm gramming ing 11.1 Intr Introduc oduction tion . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Static Content Content and Dynamic Content . . . . . . . . . . . . 11.2.1 11.2. 1 The Hyperte Hypertext xt Markup Markup Langu Language age . . . . . . . . . . 11.2.2 The World Wide Web . . . . . . . . . . . . . . . . 11.3 What is CGI? . . . . . . . . . . . . . . . . . . . . . . . . . 11.4 Your First First CGI Program . . . . . . . . . . . . . . . . . . . 11.5 GET vs. POST POST . . . . . . . . . . . . . . . . . . . . . . . . . 11.6 File Up Upload load . . . . . . . . . . . . . . . . . . . . . . . . . . 11.7 Important HTTP Header Header Fields and Environment Environment Variables Variables 11.7.1 CGI-Relate CGI-Related d Environment Variables . . . . . . . . . 11.7.2 11.7. 2 HTTP Hea Header der Field Fieldss . . . . . . . . . . . . . . . . . 11.8 Serve Serverr Side Side Includes Includes . . . . . . . . . . . . . . . . . . . . . . 11.9 Secu Security rity Iss Issues ues . . . . . . . . . . . . . . . . . . . . . . . . 11.9.1 11.9. 1 Wh Whyy Should Should I Care? Care? . . . . . . . . . . . . . . . . . 11.9.2 11.9. 2 Some Form Formss of Attack Attack Expl Explained ained . . . . . . . . . . 11.9.3 11.9. 3 Safe CGI Script Scripting ing Guideli Guidelines nes . . . . . . . . . . . . A How How A Ha Hash sh Work orkss A.1 Prog Program ram Listi Listing ng of Exampl Examplee Implem Implementat entation ion A.2 A. 2 Ov Overv ervie iew w . . . . . . . . . . . . . . . . . . . A.3 Pri Princi nciple pless . . . . . . . . . . . . . . . . . . . A.4 No Notes tes on Impl Implement ementation ation . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
B Admi Adminis nistrat tration ion B.1 CP CPAN AN . . . . . . . . . . . . . . . . . . . . . . . . . B.1.1 B.1. 1 Ac Acces cessing sing the Module Module Datab Database ase on the the Web Web . B.1.2 B. 1.2 Pa Packa ckage ge Man Manage agers rs . . . . . . . . . . . . . . B.1.3 B.1. 3 Inst Installing alling Mod Modules ules using CP CPAN.p AN.pm m . . . . . B.1.4 Installing Modules — The Traditional Way .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . .
. . . . .
. . . . . . . . . . . . .
149 149 149 150 151 151 152 152 155 159 159 159 160 163
. . . . . . . . . . . . . . . .
169 169 169 169 170 172 174 178 180 182 182 183 184 186 187 187 190
. . . .
193 193 198 199 199
. . . . .
201 201 201 201 202 203
C Setting Setting Up A Web Server 205 C.1 C. 1 Ap Apac ache he . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 C.1.1 Micr Microsof osoftt Wi Windows ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 C.1. C. 1.2 2 Uni nixx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
CONTENTS D A Uni nix x Pr Prim imer er D.1 Intr Introduct oduction ion . . . . . . . . . . . . . . . D.1.1 Wh Whyy Should Should I Care Care About About Unix? . D.1. .1.2 2 Wh What at Is Unix? . . . . . . . . . . D.1.3 The Over Overall all Stru Structur cturee . . . . . . D.2 Filesystems and Proces Processes ses . . . . . . . . . D.2. .2.1 1 Ove Overvie rview w . . . . . . . . . . . . . D.2.2 Sym Symbolic bolic Links and Har Hard d Links . D.2.3 Pe Permis rmission sion and Owners Ownership hip . . . D.2. .2.4 4 Pr Proce ocess sses es . . . . . . . . . . . . . D.2.5 The Spec Special ial Pe Permis rmission sion Bits . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
v 213 213 213 213 214 215 215 216 220 222 223
E In Th Thee Nex extt Ed Edit itio ion n
225
Index
226
vi vi
CON CONTEN TENTS
Preface If you are looking for a free Perl tutorial that is packed with everything you need to know to get started on Perl programming, look no further. Presenting before you is probably the most comprehensive comprehensive Perl tutorial on the Web, the product of two years of diligence seeking reference from related books and Web sites. Perl is a programming language that is offered at no cost. So wouldn’t it be nice if you can also learn it at no cost? Packed with some background knowledge of programming in C++ and Visual Basic, when I started learning Perl several years ago, I couldn’t even find one good online tutorial that covered at least the basics of the Perl Perl language and was free. free. Most Most Perl Perl tutorials tutorials I could could find merely merely covered covered the very basic topics such as scalar/list assignment, operators and some flow control structures etc. On the other hand, although I have accumulated accumulated certain levels of experience in a number of programming languages, the official Perl manual pages are are quite technical technical with whole pages of jargons that I was not very familiar with. As a result, the book “Learning Perl” written Perl” written by Larry Wall, the inventor inventor of the Perl language, naturally became the only Perl textbook available. The O’Reilly Perl Series present the most authoritative and well-written resources on the subject written by the core developers of Perl. While you are strongly recommended recommended to grab one copy of each if you have the money, money, they are not n ot so cheap, though, and that’s the motive behind my writing of this tutorial — so that more people with n o programming background can start learning this stupendous and powerful language in a more cost-effective way. Although this tutorial covers a rather wide range of topics, similar to what you can find in some other Perl guidebooks, you are strongly encouraged to read those books too, since their paedagogies of teaching may suit you more. Here are several features of this tutorial:
As this is not a printed book, I will constantly add new materials to this tutorial as needed, thus enriching the content of this tutorial. Moreover, in order to help me improve the quality of this tutorial, it is crucial for you to forward me your comments and suggestions so that I can make further improvements to it.
Earlier drafts of this tutorial were published in HTML format on my Web site. In response to requests made from several visitors, this tutorial has been made available in PDF format for download. I hope this this will help those who are charged on time basis basis for connecting to the the Internet. Internet. This A tutorial is typeset in LTEX, a renowned document typesetting system that has been widely used in the academic community on Unix-compatible systems (although it is available on nearly any operating systems you can think of). The HTML version has been discontinued, until a solution can be found which allows both versions to be generated from the same source base.
You will find a list of Web links and an d references to book chapters after each chapter where applicable which contains additional materials that ambitious learners will find helpful to further your understanding of the subject. vii
vi viii
Prefac efacee
Througho Throughout ut the text text there would be many examples. examples. In this tutorial, tutorial, you will find two types of examples — examples and illustrations. illustrations. Illustrations are intended intended to demonstrate demonstrate a particular concept concept just mentioned, mentioned, and are shorter shorter in general. general. You will find them embedded embedded inline throughout the tutorial. On the other hand, examples are more functional and resemble practical scripts, and are usually simplified versions of such. They usually demonstrate how different parts of a script can work together to realize the desired functionalities or consolidate some important concepts learned in a particular chapter. chapter.
If applicable, there will be be some exercises exercises in the the form of concept consolidation questions as well as programming exercises at the end of each chapter to give readers chances to test how much they understand the materials learned from this tutorial and apply their knowledge through practice.
This is the First Edition of the Perl 5 Tutorial. It primarily focuses on fundamental Perl programming knowledge that any Perl programmer programmer should should be familiar with. I start with some basic ideas behind comcomputer programming in general, and then move on to basic Perl programming with elementary topics such as operators and simple data structures. The chapter on scoping and subroutines is the gateway to subsequent, but more advanced topics topics such as references references and object-oriented programming. The remaining chapters are rather assorted in topic, covering the use of filehandles, file I/O and regular expressions in detail. detail. There is also a dedicated dedicated chapter on error handling which discusses facilities facilities that you can use to locate logical errors and enhance program security. The final chapter on CGI programming builds builds on knowledge knowledge covered covered in all earlier chapters chapters.. Readers Readers will learn how to write a Perl Perl program that can be used for dynamic scripting on the World Wide Web. However short, the main text already embraces the most important fundamental subjects in the Perl programming language. In the appendices, instructions are given on acquiring and installing Perl modules, setting up a basic but functional CGI-enabled Web server for script testing, and there is a voluminous coverage of Unix fundamentals. As much of Perl is based on Unix concepts, I believe a brief understanding of this operating system is beneficial to Perl programmers. An appendix is also prepared to give my readers an idea of the internal structur structuree of general general hashes. hashes. While While authoring authoring of this tutori tutorial al cannot procee proceed d indefinitel indefinitelyy, topics topics that were were planned but cannot be included in this edition subject to time constraints are deferred to the Second Edition. A list of these topics appear at the end of this document for your reference. In the second release candidate of this tutorial I made an audacious attempt of adding into it two topics that are rarely discussed in most Perl literature. The first is the Error CPAN CPAN module for exception handling. The second attempt, which is an even more audacious one, is an introduction of the finite-state automaton (FSA) for construction of complex regular expressions for pattern matching. While FSA is a fundamental topic in Computer Science (CS) studies, this is seldom mentioned outside the CS circle. Although there is a high degree of correspondence between regular expressions and FSA, this may not be at all obvious to a reader without relevant background, despite I have avoided rigorous treatment of the topic and tried to explain it in a manner that would be more easily communicable to fellow readers. I would like to emphasize this topic is not essential in Perl programming, and I only intend to use it as a tool to formulate better patterns. Feel free to skip it if that is not comfortable to you and I require your feedback of whether these topics can help you as I originally intended. It is impo importa rtant nt for for me to reit reiter erat atee that that this this docu docume ment nt is not not inte intend nded ed to be a subs substi titu tute te for for the the offic officia iall Perl erl manual pages (aka man pages) pages) and other official Perl literature. In fact, it is the set of manual pages that covers the Perl language in sufficiently fine detail, and it will be the most important set of document after after you have accumulat accumulated ed certain level of knowledge knowledge and programm programming ing experience. experience. The Perl man pages are written written in the most concise concise and correct correct technical technical parlance, parlance, and as a result result they are not very suitable for new programmers to understand. The primary objective of this tutorial is to bridge the gap so as to supplement readers with sufficient knowledge to understand the man pages. Therefore, this tutorial presents a different perspective perspective compared with some other Perl guidebooks available at your local bookstores from the mainstream computer book publishers. With a Computer Science background, I
ix intend to go more in-depth into the principles which are central to the study of programming languages in general. Apart from describing the syntax and language features of Perl, I also tried to draw together the classical programming language design theories and explained how they are applied in Perl. With this knowledge, it is hoped that readers can better understand the jargons presented in manual pages and the principles behind. Perl is attributed by some as a very cryptic language and is difficult to learn. However, those who are knowledgeable about programming language design principles would agree Perl implements a very rich set of language features, and therefore is an ideal language for students to experiment with different programming language design principles taught in class in action. I do hope that after you have finished reading this tutorial you will be able to explore the Perl horizons on your own with confidence and experience the exciting possibilities associated with the language more easily. “To help you learn how to learn” has always been the chief methodology followed in this tutorial. Time flies. Today when I am revising this preface, which was actually written before I made my initial preview release in late 2001 according to the timestamp, I am aghast to find that it has already been nearly two years since I started writing it. Indeed, a lot of things have changed in two years. Several Perl manpages written in tutorial-style have been included into the core distribution, which are written in a more gentle way targeted at beginners. There are also more Perl resources online today than there were two years ago. However, I believe through preparing this tutorial I have also learnt a lot in the process. Despite I started this project two years ago, a major part of the text was actually written in a window of 3 months. As a result, many parts of the tutorial were unfortunately completed in a hasty manner. However However,, through through constant constant refinemen refinementt and rewriting rewriting of certain certain parts of the tutorial, tutorial, I believe believe the Second Second Edition will be more well-organized and coherent, while more advanced topics can be accommodated as more ample time is available. At last, thank you very much for choosing this tutorial. Welcome to the exciting world of Perl programming!
Bernard Chan in Hong Kong, China 15th September, 2003
x
Preface
Typographical ypog raphical Conventions Conventions Although care has been taken towards establishing a consistent typographical convention throughout this tutorial, considering this is the first time I try to publish in LATEX, slight deviations may be found in certain parts of this document. Here I put down the convention to which I tried to adhere: Elements in programming languages are typeset in monospace monospace font. Important terms are typeset in bold. bold. Profound sayings or quotes are typeset in italic . In source code listings, very long lines are broken into several lines. ¶ is placed wherever a line break occurs.
Releas Re leasee Histo History ry
30th Augu ugust, 2003 2003
Firs irst Editi ditio on, Releas leasee Cand Candid idat atee 1
15th Sept Septem embe berr, 20 2003 03
Firs Firstt Edit Editio ion, n, Rele Releas asee Cand Candid idat atee 2
01st Oct October ober,, 2003 2003
Firs Firstt Edit Editio ion, n, Relea elease se Cand Candid idat atee 3
31st December, 2003
First Edition
About About The Author Author
Bernard Chan was born and raised in Hong Kong, China. He received his Bachelor’s Degree in Computer puter Engineering Engineering from the Univers University ity of Hong Kong. His major interests interests in the field include include information system security, security, networking and Web Web technologies. He carries a long-term career objective of becoming an avid technical writer in the area of programming. His most notable publication is the Perl 5 Tutorial .
Chapter 1
Introdu Introduction ction to to Programmi Programming ng 1.1 1.1
What hat is Perl? erl?
Extracted from the perl manpage, “Perl is an interpreted high-level programming language developed by Larry Wall.” If you have not learnt any programming languages before, as this is not a prerequisite of this tutorial, this definition may appear exotic for you. The two keywords that you may not understand are “interpreted” and “high-level”. Because this tutorial is mainly for those who do not have any programming experience, it is better for me to give you a general picture as to how a computer program is developed. This helps you understand this definition.
1.2 A Trivial rivial Introd Introducti uction on to Comput Computer er Pr Progra ogrammi mming ng You should should know that, regardl regardless ess of the programming programming language you are using, using, you have to write something that we usually refer to as source code, code, which include a set of instructions for the computer to perform perform some some operations operations dictated dictated by the programmer programmer.. There There are two ways as to how the source source code can be executed by the Central Processing Unit (CPU) inside your computer computer.. The first way is to go through two processes, compilation and linking , to transform the source code into machine code, code, which is a file consisting of a series of numbers only. This file is in a format that can be recognized by the CPU readily, readily, and does not require any external programs for execution. execution. Syntax errors are detected detected when the program program is being compiled. compiled. We describe this executabl executablee file as a compiled program. program. Most Most softsoftware programs (e.g. most EXEs for MS-DOS/Windows) MS-DOS/Windows) installed in your computer fall fall within this ty pe. NOTES There are some subtleties, though. For example, the compiler that comes with with Visual Basic 6 Learning Edition translates source code into p-code (pseudo code) which has to be further convert converted ed to machine code at runtime. Such an EXE is described described as interpreted interpreted instead. instead. Therefore, not all EXEs are compiled. On the other hand, although Java is customarily considered an interpreted language, Java source files are first compiled into bytecode by the programmer, so syntactical errors can be checked at compile time.
Another way is to leave the program uncompiled (or translate the source code to an intermediate level 1
2
Chap Chapte terr 1 Intr Introdu oduct ctio ion n to Prog Program rammi ming ng
between machine code and source source code, e.g. Java). However, However, the program cannot be executed executed on its own. Instead, an external program has to be used to execute the source code. This external program is known as an interpreter, interpreter, because it acts as an intermediary to interpret the source code in a way the CPU can understand. Compilation is carried out by the interpreter before execution execution to check for syntax errors and convert the program into certain internal form for execution. Therefore, the main difference between compiled programs and interpreted languages is largely only the time of compilation phase. Compilation of compiled programs is performed early, while for interpreted programs it is usually performed just before the execution phase. Every approach has its respective respective merits. Usually, Usually, a compiled program only has to be compiled once, and thus syntax checking checking is only performed performed once. What What the operating operating system system only needs to do is to read the compiled program and the instructions encoded can be arranged for execution by the CPU directly directly.. However However,, interpr interprete eted d programs programs usually have to perform perform syntax check check every time the program program is execute executed, d, and a further further compilation compilation step is needed. needed. Therefor Therefore, e, startup startup time of compiled compiled programs programs are usually shorter shorter and executi execution on of the program is usually faster. faster. For two functionally functionally equivalent programs, a compiled program generally gives higher performance than the interpreted program. Therefore, Therefore, performance-critical performance-critical applications are generally compiled. compiled. However, However, there are a number number of factors, factors, e.g. optimizati optimization, on, that influence influence the actual performan performance. ce. Also, Also, the end user of a compiled program does not need to have any interpreters installed in order to run the program. This This conv conveni enienc encee facto factorr is importan importantt to some users. users. On the other other hand, hand, interp interpre rete ters rs have to be installed in order to execute execute a program that is interpreted. interpreted. One example is the Java Virtual Machine (JVM) that is an interpre interpreter ter plugged plugged into your browser browser to support support Java applets. applets. Java Java source source files are translated into Java bytecode, bytecode, which is then executed executed by the interpret interpreter er.. There There are some drawbacks drawbacks for a compil compiled ed program program.. For For exampl example, e, every every time time you you would would like to test test your your softwar softwaree to see if it works works properl properlyy, you have have to compile compile and link link the program program.. This This makes makes it rather rather annoying annoying for programmers to fix the errors in the program (debug ( debug ), ), although the use of makefiles alleviates most of this hassle hassle from from you. Because Because compilation compilation translates translates the source source code code to machine code which can be executed by the hardware circuitry in the CPU, this process creates a file in machine code that depends on the instruction instruction set of the computer (machine-dependent). On the other hand, interpreted programs are usually platform-independent, platform-independent, that is, the program is not affected by the operating system system on which the program program is execute executed. d. Therefor Therefore, e, for example, example, if you have a Java applet on a Web site, it can most probably be executed correctly regardless of the operating system or browser a visitor is using. It is also easier to to debug an interpreted interpreted program because repeated repeated compilation compilation is waived.
TERMINOLOGY Instruction set
refers to the set of instructions that the CPU executes. There are a number of types of microproces microprocessors sors nowadays. nowadays. For example, example, IBM-comp IBM-compatible atible PCs are now using the Intel-bas Intel-based ed instruction instruction set. This is the instruction instruction set that most computer computer users users are using. Another prominent example is the Motorola 68000 series microprocessors in Macintosh comput computers ers.. There There are some other other micropr microproce ocess ssor or types which which exist exist in minori minority ty.. The instruction instruction sets of these microproces microprocessors sors are different different and, therefore therefore,, a Window Windowss program program cannot be executed executed unadapted on a Macintosh Macintosh computer computer.. In a more technical technical parlance, parlance, architectures. different microprocessors have different instruction set architectures
Recall Recall that I mentioned mentioned that a compiled compiled program program consists consists entirely entirely of numbers. numbers. Because Because a CPU is actually actually an electroni electronicc circuit, circuit, and a digital circuit circuit mainly deals with Booleans Booleans (i.e. 0 and 1), so it is obvious obvious that programs programs used by this circuit circuit have to be sequences sequences of 0s and 1s. This is what machine code actually is. However, However, programming entirely with numbers is an extreme deterrent to computer computer
1.3 1.3
Scri Script ptss vs. vs. Progr rogram amss
3
programm programming, ing, because because numeric programming programming is highly highly prone prone to mistakes mistakes and debugging debugging is very difficult. Therefore, Therefore, assembly language was invented to allow programmers programmers to use mnemonic names to write programs. programs. An assembler assembler is used to translate translate the assembly assembly language source source into machine machine code. Assembly language is described as a low-level programming language, because the actions of an assembly language program are mainly hardware operations, for example, moving bits of data from one memory location to another. Programming using assembly language is actually analogous to that of machine code in disguise, so it is still not programmer friendly enough. Some mathematicians and computer scientists began to develop languages which were more machineindepe independe ndent nt and intuit intuitiv ivee to progr programm ammers ers that that toda todayy we refer refer to as high-level programming languages. languages. The first several high-level high-level languages, languages, like FORTRAN FORTRAN,, LISP, LISP, COBOL, COBOL, were were designed designed for specialized purposes. It was not until BASIC (Beginner’s All-purpose Symbolic Instruction Code) was invented in 1966 that made computer programming unprecedentedly easy and popular. It was the first widely-used high-level language for general purpose. Many programmers nowadays use C++, another high-level language, to write software programs. The reason why we call these “high-level languages” is that they were built on top of low-level languages and hid the complexity of low-level languages from the programmers. All such complexities complexities are handled by the interpreters or compilers compilers automatically. automatically. This is an important design concept in Computer Science called abstraction. abstraction. That’s enough background information and we can now apply the concepts learned above to Perl. Perl (Practical Extraction and Reporting Language) was designed by Larry Wall, who continues to develop newer versions versions of the Perl language for the Perl Perl community community today. today. Perl Perl does not create standalone standalone programs programs and Perl programs programs have have to be execut executed ed by a Perl Perl interpr interpreter eter.. Perl Perl interpreter interpreterss are now available for virtually any operating system, including but not limited to Microsoft Windows (Win32) and many flavours flavours of Unix. Unix. As I quoted above, above, “Perl is a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information.” This precise description best summarizes the strength of Perl, mainly because Perl has a powerful set of regular expressions with which programmers can specify search criteria (patterns) precisely. precisely. You are going to see a whole chapter devoted to regular expression in Chapter 9. Perl is installed on many Web servers nowadays for dynamic Web CGI scripting. Perl programs written as CGI applications are executed executed on servers where the Perl source files are placed. placed. Therefore, Therefore, there is no need to transfer the Perl source to and from the server (as opposed to client-side scripts like JavaScript or Java applets). Guestbooks, discussion forums and many powerful applications for the Web can be developed using Perl. There is one point which makes Perl very flexible — there is always more than one approach to accomplish a certain task, and programmers can pick whatever approach that best suits the purpose.
1.3 Scripts Scripts vs. Pr Progra ograms ms There has always been some arguments over whether to use the term “script” or “program” for Perl source files. In general, a piece of code that is executed by hardware or a software interpreter, written in some kind of programming programming languages, languages, is formally formally called a “program “program”. ”. This is a general general term that applies to programs written in machine instructions, or any programs that are compiled or interpreted. However, it is also common today to hear that people use the term “script” to refer to programs that are interpreted, especially those executed on the command line. In my opinion, it is not important to draw a distinction between the two terms as both are considered equally acceptable and understandable nowadays. In many situations people just use both interchangeably. interchangeably.
4
Chap Chapte terr 1 Intr Introdu oduct ctio ion n to Prog Program rammi ming ng
I am more inclined towards calling Perl programs and CGI programs running on a Perl backend as scripts, so I will adhere to this terminology in this tutorial.
1.4 1.4
An Ov Overvi erview ew of the the Soft Softwa ware re Deve Develo lopm pmen entt Pr Proce ocess ss
An intuitive intuitive software software development development process process is outlined outlined below. below. Note Note that this proces processs is not tailored tailored for Perl Perl programm programming ing in particular particular.. It is a general development development proces processs that can be applied applied to any programming projects projects with any programming languages. For additional notes specific specific to Perl, please refer to the next chapter. Because this tutorial does not assume readers to have any programming experience, it is appropriate for me to give you an idea as to the procedure you will most probably follow when you write your programs. In general, the process of development of a software software project could be broken broken down into a number of stages. Here is an outline of the stages involved:
Requirements Analysis First First you need to identify identify the requir requirement ementss of the project. project. Simply Simply speaking, speaking, you will need to decide what your program should should do (known as functional requirements requirements), ), and note down other requirements that are important but not related to the functions of your program (known as non-functional requirements requirements), ), for example, a requirement requirement that the user interface should be user friendly. friendly. You have to make a list of the requirements, requirements, and from it you will need n eed to decide whether w hether you have the capability capability to complet completee them. them. You may also want to prioritiz prioritizee them such that the most important functionalities are developed first, and other parts can be added subsequently.
Systems Design From From the requi require remen ments ts determ determine ined d you you can then then define define the scope scope of the proje project. ct. Inste Instead ad of puttin puttingg the whole program in one piece, we will now organize the program into several components (or subsystems — a part of the entire entire system system). ). As we will discuss discuss later later in this tutorial, tutorial, modulariz modularization ation facilitates code reuse and make correction of bugs (debug) easier. Two major models exist today — decomposition based on functions and decomposition based on objects. After you have fixed the model, you decide on which functions or object methods are to be associated with which source file or object, and determine how these components interact with each other to perform the functionaliti functionalities. es. Note Note that you don’t need to decide decide on how these source source files or objects are implem implement ented ed in real real sourc sourcee code code at this this stage stage — it is just just an overa overall ll view view of the inte interac ractio tion n betwee between n the components. We emphasize functional decomposition in the first part of the tutorial, while object-oriented programming will be covered in a later part of this tutorial.
Program Design After we have determined how the components interact with each other, we can now decide how each function function or object method method is implemente implemented. d. For each function, function, based on the actions to perform you have to develop an algorithm, algorithm, which is a well-defined programming-languageindependent independent proced procedure ure to carry out the actions specified. specified. You may want to use a flowchart flowchart or some pseudocode to illustrate illustrate the flow of the program. program. Pseudoc Pseudocode ode is expressed expressed in a way resembling real programming source code, except language-dependent constructs are omitted. As pseudocode is language independent, you can transform an idea from pseudocode pseudocode to source code in any programming languages very easily. There isn’t a single standardized pseudocode syntax. In many cases, pseudocode can even be written in English-like statements because pseudocode is written to demonstrate how a program is supposed to work, and provided it communicates the idea clearly clearly it suffices suffices.. It is up to you as the author author to express express pseudocode pseudocode in whatever way the algorithm is best illustrated.
1.4 An Overview Overview of the Softw Software are Develo Developm pment ent Proce Process ss
5
Coding This is largely the continuation of the Program Design stage to transform your algorithm into programming language constructs. If you have worked out the algorithm properly this should be a piece of cake.
Unit Testing Unit testing corresponds corresponds to Program Design. As each function or object method has a predefined behaviour, they can be tested individually to see if such behaviour agree to that defined. Most of the time when we are talking about debugging, we are describing this stage.
Systems Testing Systems Systems Testing Testing corresponds to System System Design. This is to test if the components interact with each other in exactly the same way as designed in the Systems Design stage.
Requirements Validation This corresponds to requirements analysis. The software developed is compared against the requirements to ensure each functionality has been incorporated into the system and works as expected.
Maintenance By now the software software has been developed developed but you cannot simply simply abandon it. Most Most probably probably we still need to develop later versions, or apply patches to the current one as new bugs are found in the program. Software for commercial commercial distribution distribution especially needs investment of a lot of time and effort at this stage capturing user feedback, but software not distributed commercially commercially should also pay attention to this stage as this affects how well your software can be further developed.
Of course, for the examples in this tutorial that are so short and simple we don’t need such an elaborate development procedure. However, you will find when you develop a larger-scale project that having a well-defined procedure procedure is essential to keep your development process in order. order. This is just one of the many process models in existence today. Discussion of such process models can be found found in many many fundament fundamental al text text for for Software Engineering , and are beyond the scope scope of this tutorial. Actually, Actually, what I have presented was a variant of the Waterfall process model, and is considered considered one that, if employed, is likely to delay project schedules and result in increased costs of software development. The reason reason I present present it here is that the Water Waterfall fall model is the easiest easiest model to understand. understand. Because Because presentation of process models is out of the scope of the tutorial, some Web links will be presented at the end of this chapter from which you will find selected texts describing process models, including the Rational Unified Process which which I recomme recommend nd as an improve improved d proces processs model model for larger-scal larger-scalee development projects. projects. Adoption of an appropriate process process model helps guide the development proprocess with optimized usage of resources, resources, increased productivity and software that are more fault-tolerant.
Summary ”
Source code include a set of instructions to be executed by the computer through levels of translation.
”
Low-level programming languages involves architecture-dependent programming with machine code or assembly language.
”
High-level programming languages are built on top of low-level languages and source programs can usually be platform-independent.
”
Source programs are either explicitly precompiled into object code, or are implicitly compiled before execution by the interpreter.
6
Chap Chapte terr 1 Intr Introdu oduct ctio ion n to Prog Program rammi ming ng
”
Perl is an interpreted high-level programming language developed by Larry Wall.
”
Following a well-defined software development process model helps keep the development process systematic and within budgets.
Web Links 1.1
Evolution of Programming Languages Evolution http://lycoskids.infoplease.com/ce6/sci/A0860536.html
1.2
Rational Unifie Unified d Proces Processs Whitep Whitepapers apers http://www.rational.com/pro http://www.rational.com/products/rup/whitepapers.jsp ducts/rup/whitepapers.jsp
Chapter 2
Getti Ge tting ng Start Started ed 2.1 2.1
What can can Perl erl do?
I understand it is a full wastage of time for you to have read through half of a book to find that it is not the one you are looking for. Therefore, I am going to let you know what you will learn by following this tutorial as early as possible. If you are looking for a programming language to write an HTML editor that runs on the Windows platform, or if you would like to write a Web browser or office suite, then Perl does not seem to be an appropriate language for you. C/C++, Java or (if you are using Windows) Visual Basic are likely to be more appropriate choices for you. Although it appears that Perl is not the optimum language for developing applications with a graphical user interface (but you can, with Perl/Tk or native modules like WIN::GUI), it is especially strong in doing text manipulation and extraction of useful information. Therefore, with database interfacing it is possib possible le to build build robus robustt applic applicati ations ons that that requi require re a lot of text text proc process essing ing as well well as databas databasee manage managemen ment. t. Perl is the most popular scripting language used to write scripts that utilize the Common Gateway Interface (CGI), and this is how most of us got to know this language in the first place. A cursory look at the CGI Resource Index Web site site provided provided me with a listing of about 3000 Perl CGI scripts, compared compared with only 220 written in C/C++, as of this writing. There are quite many free Web hosts that allow you to deploy custom Perl CGI scripts, but in general C/C++ CGI scripts are virtually only allowed unless you pay. In particular, there are several famous programs written in Perl worth mentioning here:
YaBB is an open open sourc sourcee bullet bulletin in boa board rd syste system. m. While While provi providin dingg users users with many many advanc advanced ed featu feature ress that could only be found on commercial products, products, it remains as a free product. product. Many webmasters webmasters use YaBB to set up their BBS. Another popular BBS written in Perl is ikonboard ikonboard,, featuring a MySQL/PostgreSQ MySQL/PostgreSQL L database back-end.
Thanks to the powerful pattern matching functions in Perl, search engines can also be written in Perl with unparalleled ease. Perlfect Search is a very good Web Web site indexing and searching system written in Perl.
You will learn more about Perl CGI programming in Chapter 11 of this tutorial.
7
8
Chap Chaptter 2 Gett Gettin ingg Star Startted
2.2 Compari Comparison son with Other Other Pr Program ogrammin mingg Langu Language agess There are many programming languages in use today, each of which placing its emphasis on certain applicatio application n domains and features. features. In the following section section I will try to compare compare Perl with several popular programming languages for the readers to decide whether Perl is appropriate for you.
2.2. 2.2.1 1
C/C+ C/C++ +
Perl is written in the C programming language. C is extensively used to develop many system software. C++ is an extension of C, adding various new features such as namespaces, templates, object-oriented programming and exception handling etc. Because C and C++ programs are compiled to native code, startup times of C/C++ programs are usually very short and they can be executed very efficiently. Perl allows you to delegate part of your program in C through the Perl-C XS interface. This Perl-C binding is extensively used by cryptographic modules to implement the core cryptographic algorithms, because such modules are computation-intensive. computation-intensive. While C/C++ is good for performance-critical applications, C/C++ suffers a number of drawbacks. First, C/C++ programs are platform dependent. A C/C++ program written on Unix is different from one on Windows because the libraries available on different different platforms are different. Second, because C/C++ is a very structured language, its syntax is not as flexible as scripting languages such as Perl, Tcl/Tk or (on Unix platforms) bash. If you are to write w rite two functionally equivalent programs in C/C++ and Perl, Perl, very likely likely the C/C++ version version requires requires more lines of code code compare compared d with Perl. Perl. And also, improperly written C/C++ programs are vulnerable to memory leak problems where heap memory allocated are not returned when the program exits. On a Web Web server running 24 ×7 with a lot of visitors, visitors, a CGI script with memory leak is sufficient to paralyze the machine.
2.2. .2.2
PHP PHP
Perl has been the traditional language of choice for writing server-side CGI scripts. However, in recent years there has been an extensive migration from Perl to PHP. PHP. Many programmers, especially those who are new to programming, have chosen PHP instead of Perl. What are the advantages of PHP over Perl? PHP is from its infancy Web-scripting oriented. Similar to ASP or JSP, JSP, it allows embedding of inline PHP code inside HTML documents that makes it very convenient to embed small snippets of PHP code, e.g. to update a counter when a visitor views a page. Perl needs Server Side Includes (SSI) or an additional additional package “eperl” “eperl” to implement implement a similar similar functionality functionality.. Also, Also, it inherits its language language syntax from from a number number of languages languages so that it has the best features features of many different different languages languages.. It mainly inherits from C/C++, and portions from Perl and Java. It uses I/O functions similar to that in C, that are also inherited into Perl, so it is relatively easy for Perl programmers programmers to migrate to PHP. PHP. While PHP supports the object-oriented paradigm, most of its functionalities are provided through functions. When PHP is compiled the administrator decides the sets of functionalities to enable. This in turn determines the sets of functions enabled in the PHP installation. I’m personally sceptical of this approach, approach, because because in practice practice only a small subset subset of these these functions functions is frequently frequently used. On the other hand, Perl only has a small set of intrinsic functions covering the most frequently used functionalities. Other Other functionali functionalities ties are delegated delegated to modules which are only installed installed and invoke invoked d as needed. As I will introduce shortly and in Appendix B, the Comprehensive Perl Archive Network (CPAN) contains a comprehensive and well-organized listing of ready-made Perl modules that you can install and use very easily.
2.3 2.3 What hat do I need need to lear learn n Perl? erl?
2.2. 2.2.3 3
9
Java Java/J /JSP SP
Sun Microsystems developed the Java language and intended to target it as a general purpose programming language. It is from the ground up object-oriented and platform independent. Functionalities are accesse accessed d through through the Java Java API, consistin consistingg of hierarchie hierarchiess of classes similar similar to that of Perl. Perl. Java Java Server Pages (JSP) is a Web scripting environment similar to ASP except with a Java syntax. Similar to C/C++, the Java syntax is very structured and thus are not as flexible as scripting languages like Perl. Also, Java itself is not just an interpreter, it is a virtual machine over which programmers are totally abstracted from the underlying operating system platforms, which allows the Java API to be implemented on top of this platform-independent layer. For those who have programmed in Java before, you will probably find that the Java Virtual Machine takes rather long time to load, especially on lower-end systems with limited computational power. power. This defers the possibility of widespread deployment of Java programs. While Perl is not strictly a general-purpose programming language like Java, I found it difficult to compare Perl and Java because of their different natures. However, if confined to the purpose of Web server scripting, I generally prefer Perl Perl to JSP for its flexibility and lightweight performance. Despite this, I feel that Java is a language that is feature-rich and if time allows, you are strongly encouraged to find out more about this stupendous language, which is expecting increasing attention in mobile and embedded devices because of its platform independence.
2.2. .2.4
ASP
Active Server Pages (ASP) is only available on Windows NT-series operating systems where Internet Information Services (IIS) is installed (although alternative implementations of ASP on other system archite architectur ctures es exist, exist, e.g. Sun Chili!Soft Chili!Soft ASP, ASP, which is a commer commercial cial product product that runs on Unix, but generally considered not very stable). Running on a Windows Web server, ASP can impose a tighter integration with Microsoft technologies, so that the use of, say, say, ActiveX ActiveX data objects objects (ADO) for database access can be made a lot easier. easier. However, However, IIS is especially vulnerable to remote attacks when operated as a Web server. Numerous service packs have been released to patch the security holes in IIS and Windows NT. However, new holes are still being discovered from time to time that makes the deployment of Windows NT/IIS as the Web Web server of choice not very favourable. On the other hand, Apache, the renowned Web server for Unix and now for other operating systems as well, has far less security concerns and are less susceptible to remote attacks. Apache also has the largest installation base among all Web server software, taking up more than 60% of the market share.
2.3 2.3
What hat do I need need to learn learn Perl erl??
You don’t need to pay a penny to learn and use Perl. Basically, a text editor that handles text-only files and a working installation of the Perl interpreter are all that you will need. Under Microsoft Microsoft Windows, Notepad Notepad meets the minimum requirement. However, However, a whole page of code in black is not visually attractive in terms of readability. readability. Some text editors editors have the feature of syntax highlighting , with different parts of a statement displayed in different colours. Good colouring makes the source files more pleasurable pleasurable to look at (such colouring is used for display only and w ill not be saved to file). However, However, avoid using word processors processors like Microsoft Microsoft Word or Wordpad which add proprietary control codes codes on file save by default. The Perl interpreter interpreter does not recognize these special formats. formats. If you have to use these word processors, ensure that your files are saved as plain text ASCII format so
10
Chap Chaptter 2 Gett Gettin ingg Star Startted
Figure 2.1: Editing a Perl source file with GVIM, running on GNU/Linux
that the Perl interpreter can access them. AnyEdit and UltraEdit are nice text editors on the Windows platform. On Unix variants, emacs and vim are stupendous text editors featuring syntax highlighting profiles for most programming programming languages with a lot of powerful features. features. Fig. 2.1 shows a screenshot of a Perl source file edited with GVIM, a port of vim that runs on Windows, X-Windows with the GTK library on Unix/Linux and many other platforms. This is my favourite text editor and is used to construct my entire Web site. If you are using one of the mainstream operating systems, the perl interpreter can be downloaded from the download section of perl.com perl.com.. perl.com is the official Web site for the Perl language and you can find the download links to all available interpreter versions versions there. Choose the version which matches your your operating operating system. system. When When you go to the download page you will see two versions, versions, namely namely the stable production production release and the experimental developer’s release. release. The stable release is the version I recommend to new users, because the developer’s version is for more advanced users to beta test the new version. It may still contain bugs and may give incorrect results. The files you have to download are under the heading “binary distribution”. Do not download the source code distribution unless you know exactly exactly how to compile compile and install them. In case you are using an operating operating system system that is not listed, a good place to find a binary distribution for your operating system is the CPAN CPAN,, located at here here,, which contains a fairly comprehensive list of platforms on which Perl can run. For Windows users, most probably you should download the Activestate distribution of Perl. It is very easy to install, with some extra tools bundled in the package for easy installation of new modules. For GNU/Linux users, most probably Perl is already installed or available as RPM (Redhat Package Manager) or DEB DEB (Debian (Debian packages) formats. As many Linux distributions distributions already already have builtin support support for RPM packages, you may look at your installation discs and you are likely to find some RPM binaries for Perl Perl if it is not yet installed. installed. For other other Unix systems systems,, you may find tarballs tarballs containing containing the Perl binaries. If no binaries are available for your system, you can still build from sources by downloading the source distribution from the CPAN. To check if perl is installed on your system, simply open a
2.4 2.4 Make Make Good Good Use of Onli Online ne Resou esourc rces es
11
perl -v. If Perl is installed terminal terminal and type perl installed you will have the version version information information of Perl Perl installed installed displayed on screen. If error messages appear, you will need to install it.
Installation of Perl will not be covered in this tutorial, and you should look for the installation help documents for details.
NOTES Because Perl is an open source software, which releases the source code to the public for free, you will see the source code distribution listed. Yet for usual programming purposes there is no need to download the source files unless binary distributions are not available for your system. An exception is if you are using one of the operating systems in the Unix family (including Linux). There are already compilation tools in these operating systems and you can manually compile compile Perl from sources sources and install install it afterwards. afterwards. However However,, note that compilatio compilation n can be a very time-cons time-consumin umingg process, process, depending depending on the performan performance ce of your system. system. If you are using Linux, binary distributions in the form of RPM or DEB packages can be installed very easily easily. Only if you cannot find a binary distribution distribution for your platform platform that you are encouraged to install from source package.
2.4 Make Make Good Us Usee of Online Online Re Resou sourc rces es You may need to seek seek refere reference nce while while you you are are learni learning ng the languag language. e. As a new user user you you are not recomme recommended nded to start learning learning Perl by reading reading the man-pages man-pages or the refere reference nce manuals. manuals. They are written in strict technical parlance that beginners, especially those who do not have prior programming experience or basic knowledge in Computer Science, would find reading them real headaches. You are recommended recommended to follow this tutorial (or other tutorials or books) to acquire some basic knowledge first, and these reference documents will become very useful for ambitious learners to know more about the language, or when you have doubt on a particular subject you may be able to find the answers inside. In this course I will try to cover some important terms used in the reference materials to facilitate your your understanding understanding of the text. For the time being, you may want to have have several books on Perl for cross-referencing purposes. I have tried to write this tutorial in a way that beginners should find it easy to follo follow, w, yet you you may may need need to to consu consult lt these these boo books ks if you you have have any points points that that you you don’t don’t unders understan tand d fully fully.. Although you are not advised to read the official reference documents too early, in some later parts I may refer refer you to read a certain manpage. manpage. A manpage, on Unix/Linux Unix/Linux systems, systems, is a help document document on a particular particular aspect. aspect. To read a particular manpage, manpage, (bring up a terminal terminal if you are in X-Windo X-Windows) ws) type man followed by the name of the manpage, for example, man perlvar perlvar, the perlvar manpage will be displayed. For other platforms, manpages may usually come in the format of HTML files. Consult the documentati documentation on of your your distribution distribution for details. details. There There is an online version version of the Perl official documentation at perldoc.com perldoc.com.. It contains the Perl man pages as well as documentation of the modules shipped with Perl. In fact, there are now several manpages that are targeted at novice programmers. For instance, the perlintro manpage is a brief introduction to the fundamental aspects of the Perl language that you should master fully in order to claim yourself a Perl programmer programmer. You are also reminded of the vast varieties of Perl resources online. There are many Perl newsgroups on the USENET and mailing lists devoted to Perl. Your questions may be readily answered by expert Perl
12
Chap Chaptter 2 Gett Gettin ingg Star Startted
programmers there. Of course, try to look for a solution from all the resources you can find including the FAQs before you post! Otherwise, your question may simply be ignored. Perl Monks is also a very useful resource to Perl users. dmoz.org contains a nice selection of Perl-related sites. You can find a similar list of entries on Yahoo! Yahoo!.. Google is the best search search engine for programm programmers ers.. You can usually usually get very accurate accurate search search results results that deliver what you need. For example, by specifying the terms “Perl CGI.pm example”, example”, you will get screenfuls of links to examples demonstrating the various uses of the CGI.pm module. As you will see later, this module is the central powerhouse allowing you to handle most operations involving CGI programming with unparalleled ease. For materials not covered in this tutorial or other books, a search phrase can be constructed in a similar manner that allows you to find documentation and solutions to your questions at your fingertips. Of course, don’t forget to experiment yourself! CPAN CPAN,, the Comprehensive Perl Archive Network is a nice place where you can download a lot of useful modules contributed by other Perl programmers. By using these modules you can enforce code reuse, rather than always inventing code from scratch again. There are so many modules on the CPAN available that you would be surprised at how active the Perl community has been. Some CPAN modules are well-documented, some are not. You may need to try to fit the bits and pieces together and see if it works. This requires much time and effort, but you can learn quite a lot from this process.
2.5 The Traditional raditional “Hello “Hello World” Pr Program ogram Traditionally, the first example most book authors use to introduce a programming language is what is customarily called a “Hello World” World” program. The action of this program is extremely simple — simply displays displays the text “Hello World World”” to the screen and does nothing nothing else. For all examples in this tutorial tutorial of which source code are given in the text, you are encouraged to type them in yourself instead of executing executing the examples downloaded from my Web Web site, since it is more likely that by doing so you would understand the materials more quickly. Let’s write a “Hello World” program to see the procedures we take to develop a Perl program. If you are on Windows, it is a good practice to check if the path to the Perl interpreter has been added to the path list in C:\Autoexec.bat. In this way, you can change to the path containing your Perl source files and can run the interpre interpreter ter without specifying specifying its path. path. The setup program of your distribution distribution would would probably probably have done it for you. If it hasn’t, append the path to the end of the list and end it with a semicol semicolon. on. A typical path list looks like this, this, the last one in this example example is the path to the perl interpreter interpreter (note that your path may be different): SET PATH PATH = C:\WIN C:\WINDOW DOWS; S; C:\WIND C:\WINDOWS\C OWS\COMM OMMAND; AND; C:\WIN C:\WINDOW DOWS\SYS S\SYSTEM; TEM; C:\PERL\ C:\PERL\BIN; BIN;
For Unix/Linux, check your PATH variable and see if the directory containing the perl executable is present present (usually (usually /usr/bin). /usr/bin). You can look at the list of paths by typing echo $PATH on the command line (be careful of exact capitalizati capitalization!). on!). Look for “/usr/bin” “/usr/bin” in the colon-separ colon-separated ated values. values. On some systems, systems, the path to perl would be “/usr/local/bin” or something else, so please check carefully. carefully. You may need to modify the startup login scripts scripts like .login, .login, .bashrc, .bashrc, .profile .profile etc. so that you don’t need to set PATH or specify the full path to perl every time if perl is installed at some weird locations. A convenient workaround is to create a symbolic link in a directory included in PATH, e.g. /usr/bin that points to the perl executable. executable.
2.5 2.5 The The Tradit raditio iona nall “Hel “Hello lo World orld”” Prog Program ram
13
NOTES The use of Autoexec.bat Autoexec.bat is now obsolete starting from Windows Windows 2000. Setting of environment variables should be carried out by right-clicking on the “My Computer” icon, and then choose choose the “Prope “Properti rties” es” option. option. Now Now select select the “Adva “Advance nced” d” tab and then click click on the “Environ “Environment ment Variable Variables” s” button at the bottom. To make the perl interpret interpreter er available available to all users on the system, the path should be appended to the PATH variable in the “System variables” section. If you modify the PATH variable in the “User variables” section, only the user concerned (presumably you) will be affected.
EXAMPLE 2.1
1 2 3 4 5
#!/usr/bin/perl #!/usr/bin/perl -w # Exam Exampl ple e 2.1 2.1 - Hell Hello o Worl World d # prin print t the the text text to the the scre screen en print print "Hello, "Hello, World!\ World!\n"; n";
Here we outline the steps to create this simple program on Windows and Linux. Microsoft Windows
1.
Open Notep Notepad ad (or any any other other text edito editorr you choose choose)) and type in the sourc sourcee code shown shown above. above. Note that the line numbers on the left are for identification of lines only and do NOT type them into the text editor. Please make sure word wrap is disabled.
2.
Save the file as hello.pl. hello.pl. A few text editors, like Notepad, Notepad, usually append the the “.txt” extension to the filename when saving. You may put a pair of double quotes around the filename to circumvent circumvent this behaviour behaviour.. Also, Also, if you are using using Windows Windows 2000 or above and would like to use Notepa Notepad, d, please ensure that the file encoding is set to ANSI instead of Unicode.
3.
Bring up an an MS-DOS MS-DOS prompt prompt window and change change to the the direc directory tory containing containing your newly created created file. Say if you have have saved to ”C: ”C:\perl examples”, then type cd C:\perl examples and press Enter. Put a pair of double quotes around the path if any directories in the path contains spaces (In fact I don’t recommend placing Perl source files in directories with names containing spaces. It only complicates complicates matters).
4.
Execu Execute te the progr program am by typing typing perl perl -w hello. hello.pl pl and press enter.
Unix or GNU/Linux GNU/Linux
1.
Open any any text text editor editor (vim, (vim, emacs, emacs, pico, pico, kedit kedit ....) ....) and type in in the sourc sourcee code code shown shown above. above. Note Note that the line numbers on the left are for identification only and do NOT type them into the text editor. Please make sure word wrap is disabled.
2.
Save Save the file file as hello.pl hello.pl.. Note Note that that the path path on line 1 has has to match match the the path to perl perl on your your system system.. Also, no spaces should precede the ‘#’ character and no empty lines are allowed before this special line (traditionally known as the ‘shebang ‘shebang ’ line).
14
Chap Chaptter 2 Gett Gettin ingg Star Startted
3.
If you you are in in X-Window X-Windowss enviro environment nment,, bring up a termina terminall window. window. Change Change to the the directo directory ry containing the newly created file using the cd command.
4.
In order order to run it without without specif specifying ying the perl perl interpret interpreter er,, set the file acces accesss privilege privilege to user user exeexecutabl cutablee by using using the chmod command. The command command should be chmod press chmod u+x hello. hello.pl pl and press Enter.
5.
Execu Execute te the progr program am by typing typing ./hello.pl and then press Enter. NOTES Even if you are using Unix/Linux, it is not absolutely needed to chmod your perl source files. files. In fact, you only need to make those source source files files executable executable if you want them to be directly invoked without specifying the name of the interpreter (i.e. perl). In thi thiss case, case, the shell will look at the first line of the file to determine which interpreter is used, so the #!/usr/bin/perl line must exist. Otherwise, the file cannot be executed. If you only intend to execute the file in Unix or Linux using perl perl -w filenam filename.pl e.pl, then filename.pl need not be given an executabl executablee permission. permission. As you will learn later, later, you may have some Perl source source files that are not invoked invoked directly. directly. Instead, Instead, they are being sourced sourced from another source file and don’t need to be executable executable themselve themselves. s. For these files, you don’t need to chmod chmod them and the default permission is adequate.
If there is not any errors, you should see the words “Hello, World!” under the command prompt. For such a simple program it is not easy to make mistakes. If error messages appear, check carefully if you have left out anything, because a trivial mistake is sufficient to end up with some error messages if you are not careful. Also check if you are using the latest stable version of Perl 5. All examples in this tutorial have been tested with Perl 5.8.0 Win32 (ActiveState distribution) and Perl 5.8.0 on GNU/Linux, but it should work for other distributions or versions as well unless otherwise noted. The -w is an example of a switch. switch. You specify a switch to enable a particular interpreter feature. -w is specified so that warning wa rning messages, if any, are displayed on screen. Under no circumstances circumstances should this switch be omitted because it is important, especially as a beginner, to ensure that the code written is correct. correct. It also helps catch catch some mistakes mistakes that are otherwise difficult difficult to capture. capture. This is explained in more detail in Chapter 10 10.. A Perl script consists of statements of statements,, and each statement is terminated with a semicolon (;). A statement is rather like a sentence in human languages which carries a certain meaning. For computer languages a statement is an instruction to be performed. The core of the program program is on line 5. It is this statement statement that prints the text text delimited delimited by quotation quotation marks to the screen (in a more accurate parlance, the text is sent to the standard output, output, which is the screen by default). print() is an example of a builtin function. function. A function usually accepts a number of parameters, parameters, or arguments. arguments. Paramete Parameters rs serve to provide a function with additional additional pieces of data that are necessary necessary for its operation. operation. In the example, example, print() takes the text as parameter in order to display it on screen. A set of basic functions is provided to you by Perl for performing different actions. Some of these functions will be introduced as you progress through this tutorial. Notice Notice the strange \n at the end? It is one of the escape characters characters which will be described later in more detail. \n is used to insert a line break. Therefore, Therefore, you see a blank line before returning to the command prompt.