Tải bản đầy đủ (.pdf) (2,399 trang)

Prentice hall perl by example 4th edition nov 2007 ISBN 0132381826

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.61 MB, 2,399 trang )

PerlbyExample,FourthEdition
byEllieQuigley
Publisher:PrenticeHall
PubDate:November05,2007
PrintISBN-10:0-13-238182-6
PrintISBN-13:978-0-13-238182-6
Pages:1008
TableofContents|Index

Overview
"IpickedupacopyofJavaScriptbyExampleovertheweekend
andwantedtothankyouforputtingoutabookthatmakes
JavaScripteasytounderstand.I'vebeenadeveloperforseveral
yearsnowandJShasalwaysbeenthe"monsterunderthe
bed,"sotospeak.Yourbookhasansweredalotofquestions
I'vehadabouttheinnerworkingsofJSbutwasafraidtoask.
NowallIneedisabookthatcoversAjaxandColdfusion.
Thanksagainforputtingtogetheranoutstandingbook."
–ChrisGomez,Webservicesmanager,ZunchWorldwide,Inc.
"IhavebeenreadingyourUNIX®ShellsbyExamplebook,and
Imustsay,itisbrilliant.Mostotherbooksdonotcoverallthe
shells,andwhenyouhavetoconstantlyworkinanorganization
thatusestcsh,bash,andkorn,itcanbecomeverydifficult.
However,yourbookhasbeenindispensabletomeinlearning
thevariousshellsandthedifferencesbetweenthem…soI
thoughtI'demailyou,justtoletyouknowwhatagreatjobyou
havedone!"
–Farogh-AhmedUsmani,B.Sc.(Honors),M.Sc.,DIC,project
consultant(BillingSolutions),Comverse
"IhavebeenlearningPerlforabouttwomonthsnow;Ihavea
littleshellscriptingexperiencebutthatisit.Ifirststartedwith




LearningPerlbyO'Reilly.Goodbookbutlackingonthe
examples.IthenwenttoProgrammingPerlbyLarryWall,a
greatbookforintermediatetoadvanced,didn'thelpmemuch
beginningPerl.IthenpickedupPerlbyExample,Third
Edition–thisbookisasuperb,well-writtenprogrammingbook.I
havereadmanycomputerbooksandthisdefinitelyranksinthe
toptwo,inmyopinion.Theexamplesareexcellent.Theauthor
showsyouthecode,theoutputofeachline,andthenexplains
eachlineineveryexample."
–DanPatterson,softwareengineer,GuideWorks,LLC
"EllieQuigleyhaswrittenanoutstandingintroductiontoPerl,
whichIusedtolearnthelanguagefromscratch.Allonehasto
doisworkthroughherexamples,putzaroundwiththem,and
beforelong,you'rerelativelyproficientatusingthelanguage.
EventhoughI'vegraduatedtousingProgrammingPerlbyWall
etal.,IstillfindQuigley'sbookamostusefulreference."
–CaseyMachula,supportsystemsanalyst,NorthernArizona
University,CollegeofHealthandHumanServices
"WhenIlookatmybookshelf,IseeelevenbooksonPerl
programming.PerlbyExample,ThirdEdition,isn'tontheshelf;
itsitsonmydesk,whereIuseitalmostdaily.WhenIbought
mycopyIhadnotprogrammedinseveralyearsandmy
programmingwasmostlyinCOBOLsoIwasarankbeginnerat
Perl.IhadatthattimepurchasedseveralpopularbooksonPerl
butnothingthatreallyputittogetherforme.Iamstillnopro,
butmybookhasmanydog-earedpagesandeachoneisa
lessonIhavelearnedandwillcertainlyremember."Istillthink
itisthebestPerlbookonthemarketforanyonefroma

beginnertoaseasonedprogrammerusingPerlalmostdaily."
–BillMaples,networkdesigntoolsandautomationsanalyst,
FidelityNationalInformationServices
"WearerewritingourintrotoOSscriptingcourseandselected
yourtextforthecourse.It'sanexceptionalbook.Thelasttime


weconsidereditwasafewyearsago(secondedition).The
debuggingandsystemadministratorchaptersattheendnailed
itforus."
–JimLeone,Ph.D.,professorandchair,Information
Technology,RochesterInstituteofTechnology
"Quigley'sbookacknowledgesamajorusageofPHP.Towrite
somekindoffrontenduserinterfaceprogramthathookstoa
backendMySQLdatabase.Botharefreeandopensource,and
thecombinationhasprovedpopular.Especiallywherethefront
endinvolvesmakinganHTMLwebpagewithembeddedPHP
commands."NoteveryexampleinvolvesbothPHPandMySQL.
ThoughallexampleshavePHP.Manydemonstratehowtouse
PHPinsideanHTMLfile.Likewritinguser-definedfunctions,or
nestingfunctions.Ormakingorusingfunctionlibraries.The
functionsareakeyideainPHP,thattakeyoubeyondthe
elementarysyntax.Functionsalsoletyougainfullyusecodeby
otherPHPprogrammers.Importantifyouarepartofacoding
groupthathastodivideuptheprogrammingeffortinsome
manner."
–Dr.WesBoudville,CTO,MetaswarmInc.
TheWorld'sEasiestPerlTutorial–FullyUpdated!
PerlbyExample,FourthEdition,istheeasiest,mosthandsonwaytolearnPerl.LegendarySiliconValleyprogramming
instructorEllieQuigleyhasthoroughlyupdatedherclassicto

delivertheskillsandinformationtoday'sPerlusersneedmost–
includingall-newcoverageofMySQLdatabaseprogramming
andaPerlQuickStartdesignedtogetexperiencedusersupand
runningfast.
Quigleyilluminateseverytechniquewithfocused,classroomtestedcodeexamples,detailedline-by-lineexplanations,and
realprogramoutput.Thisexceptionallyclear,easy-tounderstandbooktakesyoufromyourfirstPerlscriptto
database-drivenapplications.It'stheonlyPerlbookyou'llever


need!
Newinthisedition:
PerlprogrammingQuickStart:makesfirst-timePerl
programmersproductiveinjusttwentypages
All-newchapteronusingthePerlDBIwiththeMySQL
database–plusaneasySQLprimertoquicklygetyou
startedprogramminganydatabase
NewintroductionstoPerlinbiology(bioinformatics)andto
mod_perl,aPerlinterpreterembeddedintheApache
server,whichallowsyoutocreatefast,dynamiccontent;
managetheApacheserver;authenticateusers;andmuch
more
Completelyupdated:
Includesmanynewandcompletelyrewrittencodeexamples
ContainsfullyrevisedCGIcoverageforbuildingdynamic
WebsiteswithPerl
CoversmodernPerl5.8conceptsandprinciples–and
providesagreatfoundationforPerl6
Morethan30,000sysadmins,powerusers,anddevelopers
haveusedpreviouseditionsofPerlbyExample
tobecomeexpertPerlprogrammers.WithPerlbyExample,

FourthEdition,youcan,too–evenifyou're
completelynewtoPerl.Afteryou'vebecomeanexpert,you'll
turntothisbookconstantlyasthebest
sourceforreliableanswers,solutions,andcode.
AbouttheCD-ROM:
TheCD-ROMincludesallcodeandfilesforthisbook'shundreds


ofexamplescripts.


PerlbyExample,FourthEdition
byEllieQuigley
Publisher:PrenticeHall
PubDate:November05,2007
PrintISBN-10:0-13-238182-6
PrintISBN-13:978-0-13-238182-6
Pages:1008
TableofContents|Index

Copyright
PraiseforEllieQuigley'sBooks
Preface
Acknowledgments
Chapter1.ThePracticalExtractionandReportLanguage
Section1.1.WhatIsPerl?
Section1.2.WhatIsanInterpretedLanguage?
Section1.3.WhoUsesPerl?
Section1.4.WheretoGetPerl
Section1.5.WhatIsCPAN?

Section1.6.PerlDocumentation
Section1.7.WhatYouShouldKnow
Section1.8.What'sNext?
Chapter2.PerlQuickStart
Section2.1.QuickStart,QuickReference
Section2.2.ChapterSummary
Section2.3.What'sNext?
Chapter3.PerlScripts
Section3.1.ScriptSetup
Section3.2.TheScript
Section3.3.PerlattheCommandLine
Section3.4.WhatYouShouldKnow


Section3.5.What'sNext?
Chapter4.GettingaHandleonPrinting
Section4.1.TheFilehandle
Section4.2.Words
Section4.3.TheprintFunction
Section4.4.TheprintfFunction
Section4.5.WhatYouShouldKnow
Section4.6.What'sNext?
Chapter5.What'sinaName
Section5.1.AboutPerlVariables
Section5.2.Scalars,Arrays,andHashes
Section5.3.ReadingfromSTDIN
Section5.4.ArrayFunctions
Section5.5.Hash(AssociativeArray)Functions
Section5.6.MoreHashes
Section5.7.WhatYouShouldKnow

Section5.8.What'sNext?
Chapter6.Where'stheOperator?
Section6.1.AboutPerlOperators
Section6.2.MixingDataTypes
Section6.3.PrecedenceandAssociativity
Section6.4.WhatYouShouldKnow
Section6.5.What'sNext?
Chapter7.IfOnly,Unconditionally,Forever
Section7.1.ControlStructures,Blocks,andCompound
Statements
Section7.2.RepetitionwithLoops
Section7.3.WhatYouShouldKnow
Section7.4.What'sNext?
Chapter8.RegularExpressions—PatternMatching
Section8.1.WhatIsaRegularExpression?
Section8.2.ExpressionModifiersandSimpleStatements


Section8.3.RegularExpressionOperators
Section8.4.WhatYouShouldKnow
Section8.5.What'sNext?
Chapter9.GettingControl—RegularExpressionMetacharacters
Section9.1.RegularExpressionMetacharacters
Section9.2.Unicode
Section9.3.WhatYouShouldKnow
Section9.4.What'sNext?
Chapter10.GettingaHandleonFiles
Section10.1.TheUser-DefinedFilehandle
Section10.2.PassingArguments
Section10.3.FileTesting

Section10.4.WhatYouShouldKnow
Section10.5.What'sNext?
Chapter11.HowDoSubroutinesFunction?
Section11.1.Subroutines/Functions
Section11.2.PassingArguments
Section11.3.Call-by-Reference
Section11.4.WhatYouShouldKnow
Section11.5.What'sNext?
Chapter12.ModularizeIt,PackageIt,andSendIttothe
Library!
Section12.1.PackagesandModules
Section12.2.TheStandardPerlLibrary
Section12.3.ModulesfromCPAN
Section12.4.WhatYouShouldKnow
Section12.5.What'sNext?
Chapter13.DoesThisJobRequireaReference?
Section13.1.WhatIsaReference?WhatIsaPointer?
Section13.2.WhatYouShouldKnow
Section13.3.What'sNext?
Chapter14.BlessThoseThings!(Object-OrientedPerl)


Section14.1.TheOOPParadigm
Section14.2.Classes,Objects,andMethods
Section14.3.AnonymousSubroutines,Closures,and
Privacy
Section14.4.Inheritance
Section14.5.PublicUserInterface—DocumentingClasses
Section14.6.UsingObjectsfromthePerlLibrary
Section14.7.WhatYouShouldKnow

Section14.8.What'sNext?
Chapter15.ThoseMagicTiesandDBMStuff
Section15.1.TyingVariablestoaClass
Section15.2.DBMFiles
Section15.3.WhatYouShouldKnow
Section15.4.What'sNext?
Chapter16.CGIandPerl:TheHyperDynamicDuo
Section16.1.StaticandDynamicWebPages
Section16.2.HowItallWorks
Section16.3.CreatingaWebPagewithHTML
Section16.4.HowHTMLandCGIWorkTogether
Section16.5.GettingInformationIntoandOutoftheCGI
Script
Section16.6.CGIandForms
Section16.7.TheCGI.pmModule
Chapter17.PerlMeetsMySQL—APerfectConnection
Section17.1.Introduction
Section17.2.WhatIsaRelationalDatabase?
Section17.3.GettingStartedwithMySQL
Section17.4.WhatIsthePerlDBI?
Section17.5.StatementsthatDon'tReturnAnything
Section17.6.Transactions
Section17.7.UsingCGIandtheDBItoSelectandDisplay
Entries


Section17.8.What'sLeft?
Section17.9.WhatYouShouldKnow
Section17.10.What'sNext?
Chapter18.InterfacingwiththeSystem

Section18.1.SystemCalls
Section18.2.Processes
Section18.3.OtherWaystoInterfacewiththeOperating
System
Section18.4.ErrorHandling
Section18.5.Signals
Section18.6.WhatYouShouldKnow
Section18.7.What'sNext?
Chapter19.ReportWritingwithPictures
Section19.1.TheTemplate
Section19.2.WhatYouShouldKnow
Section19.3.What'sNext?
Chapter20.SendItOvertheNetandSockItto'Em!
Section20.1.NetworkingandPerl
Section20.2.Client/ServerModel
Section20.3.NetworkProtocols(TCP/IP)
Section20.4.NetworkAddressing
Section20.5.Sockets
Section20.6.Client/ServerPrograms
Section20.7.TheSocket.pmModule
Section20.8.WhatYouShouldKnow
AppendixA.PerlBuilt-ins,Pragmas,Modules,andthe
Debugger
SectionA.1.PerlFunctions
SectionA.2.SpecialVariables
SectionA.3.PerlPragmas
SectionA.4.PerlModules
SectionA.5.Command-LineSwitches



SectionA.6.Debugger
AppendixB.SQLLanguageTutorial
SectionB.1.WhatIsSQL?
SectionB.2.SQLDataManipulationLanguage(DML)
SectionB.3.SQLDataDefinitionLanguage
SectionB.4.SQLFunctions
SectionB.5.AppendixSummary
SectionB.6.WhatYouShouldKnow
AppendixC.PerlandBiology
SectionC.1.WhatIsBioinformatics?
SectionC.2.ALittleBackgroundonDNA
SectionC.3.SomePerlExamples
SectionC.4.WhatIsBioPerl?
SectionC.5.Resources
AppendixD.PowerandSpeed:CGIandmod_perl
SectionD.1.WhatIsmod_perl?
SectionD.2.Themod_perlWebSite
SectionD.3.Installingmod_perl
SectionD.4.Resources
Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany

kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheUnitedStatespleasecontact:
InternationalSales

VisitusontheWeb:www.prenhallprofessional.com
LibraryofCongressCataloging-in-PublicationData
Quigley,Ellie.
Perlbyexample/EllieQuigley.—4thed.
p.cm.
Includesindex.
ISBN978-0-13-238182-


6(pbk.:alk.paper)1.Perl(Computerprogramlanguage)I.Title.
QA76.73.P22Q532007
005.13'3—dc22

Copyright©2008PearsonEducation,Inc.

Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
501BoylstonStreet,Suite900
Boston,MA02116
Fax:(617)671-3447
ISBN-13:978-0-13-238182-6
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.
Firstprinting,October2007
Editor-in-Chief
MarkL.Taub
ManagingEditor
JohnFuller
Full-ServiceProductionManager
JulieB.Nahil
ProductionEditor
DmitriKorzh,TechneGroup


CopyEditor
TechneGroup
Indexer
LarrySweazy

Proofreader
EvelynPyle
PublishingCoordinator
NoreenRegina
CoverDesigner
AlanClements
Composition
TechneGroup


PraiseforEllieQuigley'sBooks
"IpickedupacopyofJavaScriptbyExampleoverthe
weekendandwantedtothankyouforputtingoutabook
thatmakesJavaScripteasytounderstand.I'vebeena
developerforseveralyearsnowandJShasalwaysbeenthe
"monsterunderthebed,"sotospeak.Yourbookhas
answeredalotofquestionsI'vehadabouttheinner
workingsofJSbutwasafraidtoask.NowallIneedisa
bookthatcoversAjaxandColdfusion.Thanksagainfor
puttingtogetheranoutstandingbook."
—ChrisGomez,Webservicesmanager,ZunchWorldwide,
Inc.
"IhavebeenreadingyourUNIX®ShellsbyExamplebook,
andImustsay,itisbrilliant.Mostotherbooksdonotcover
alltheshells,andwhenyouhavetoconstantlyworkinan
organizationthatusestcsh,bash,andkorn,itcanbecome
verydifficult.However,yourbookhasbeenindispensableto
meinlearningthevariousshellsandthedifferences
betweenthem...soIthoughtI'demailyou,justtoletyou
knowwhatagreatjobyouhavedone!"

—Farogh-AhmedUsmani,B.Sc.(Honors),M.Sc.,DIC,
projectconsultant(BillingSolutions),Comverse
"IhavebeenlearningPerlforabouttwomonthsnow;I
havealittleshellscriptingexperiencebutthatisit.Ifirst
startedwithLearningPerlbyO'Reilly.Goodbookbutlacking
ontheexamples.IthenwenttoProgrammingPerlbyLarry
Wall,agreatbookforintermediatetoadvanced,didn'thelp
memuchbeginningPerl.IthenpickedupPerlbyExample,
ThirdEdition—thisbookisasuperb,well-written
programmingbook.Ihavereadmanycomputerbooksand
thisdefinitelyranksinthetoptwo,inmyopinion.The
examplesareexcellent.Theauthorshowsyouthecode,the
outputofeachline,andthenexplainseachlineinevery


example."
—DanPatterson,softwareengineer,GuideWorks,LLC
"EllieQuigleyhaswrittenanoutstandingintroductionto
Perl,whichIusedtolearnthelanguagefromscratch.All
onehastodoisworkthroughherexamples,putzaround
withthem,andbeforelong,you'rerelativelyproficientat
usingthelanguage.EventhoughI'vegraduatedtousing
ProgrammingPerlbyWalletal.,IstillfindQuigley'sbooka
mostusefulreference."
—CaseyMachula,supportsystemsanalyst,Northern
ArizonaUniversity,CollegeofHealthandHumanServices
"WhenIlookatmybookshelf,IseeelevenbooksonPerl
programming.PerlbyExample,ThirdEdition,isn'tonthe
shelf;itsitsonmydesk,whereIuseitalmostdaily.WhenI
boughtmycopyIhadnotprogrammedinseveralyearsand

myprogrammingwasmostlyinCOBOLsoIwasarank
beginneratPerl.Ihadatthattimepurchasedseveral
popularbooksonPerlbutnothingthatreallyputittogether
forme.Iamstillnopro,butmybookhasmanydog-eared
pagesandeachoneisalessonIhavelearnedandwill
certainlyremember.
"IstillthinkitisthebestPerlbookonthemarketfor
anyonefromabeginnertoaseasonedprogrammerusing
Perlalmostdaily."
—BillMaples,networkdesigntoolsandautomations
analyst,FidelityNationalInformationServices
"WearerewritingourintrotoOSscriptingcourseand
selectedyourtextforthecourse.It'sanexceptionalbook.
Thelasttimeweconsidereditwasafewyearsago(second
edition).Thedebuggingandsystemadministratorchapters
attheendnaileditforus."


—JimLeone,Ph.D.,professorandchair,Information
Technology,RochesterInstituteofTechnology
"Quigley'sbookacknowledgesamajorusageofPHP.To
writesomekindoffrontenduserinterfaceprogramthat
hookstoabackendMySQLdatabase.Botharefreeand
opensource,andthecombinationhasprovedpopular.
EspeciallywherethefrontendinvolvesmakinganHTML
webpagewithembeddedPHPcommands.
"NoteveryexampleinvolvesbothPHPandMySQL.Though
allexampleshavePHP.ManydemonstratehowtousePHP
insideanHTMLfile.Likewritinguser-definedfunctions,or
nestingfunctions.Ormakingorusingfunctionlibraries.The

functionsareakeyideainPHP,thattakeyoubeyondthe
elementarysyntax.Functionsalsoletyougainfullyusecode
byotherPHPprogrammers.Importantifyouarepartofa
codinggroupthathastodivideuptheprogrammingeffort
insomemanner."
—Dr.WesBoudville,CTO,MetaswarmInc.


Preface
Youmaywonder,whyaneweditionofPerlbyExample?Perl5
hasn'treallychangedthatmuch;infact,it'schangedverylittle
atallsincethethirdeditionofthisbookwaspublished.And
sincePerl6hasn'tbeenofficiallyreleased,whynotwait?Well,
considerthis.Let'ssayyouboughtanewWhirlpoolwashing
machinesixyearsago.It'srunningperfectly.Butsincethen,
themoundsoflaundrywashedbythatmachinehavecomeand
gone.Nowyou'resportinganewtrendyfashion,youhave
designersheetsandtowels,andthedetergentbrandyouuseis
hypoallergenic,nontoxic,andbiodegradable,notavailablewhen
youboughtthewasher.EventhoughPerl5haschangedvery
little,thecomputerworldhas.Itisalwaysinafluxofnew
innovations,technologies,applications,andfads,andprograms
arebeingwrittentoaccommodatethosechanges.Whether
analyzingdatafromtheGenBanksequencedatabase,writing
applicationsforaniPhone,creatingapersonalblogon
"myspace,"oradjustingtothechangesinanewVistaversion
ofWindows,somecomputerprogramisinvolved,andvery
possiblyitisaPerlprogram.Whateverthecase,weliketokeep
upwiththetimes.ThisneweditionofPerlbyExamplewas
writtenforjustthatpurpose.

Aswespeak,IamteachingPerlattheUCSC[1]extensionin
Sunnyvale,California,toagroupofprofessionalscomingfrom
allaroundtheSiliconValley.Ialwaysaskatthebeginningofa
class,"SowhydoyouwanttolearnPerl?"Theresponsesvary
from,"OurcompanyhasanauctionsiteontheWebandI'mthe
webmaster.IneedtousePerlandApachetoprocessourorder
informationandsendittoOracle,"or"Iworkinagenetics
researchgroupatStanfordandhavetosiftthroughandanalyze
massesofdata,andIheardthatifIlearnPerl,Iwon'thaveto
dependonprogrammerstodothis,"or"I'maUNIX/Linux
systemadministratorandourcompanyhasdecidedthatall
adminscriptsshouldbeconvertedtoPerl,"or"Ijustgotlaidoff
andheardthatit'sanabsolutemusttohavePerlonmy


resume."AndIamalwaysamazedatthevarietyofpeoplewho
showup:engineers,scientists,geneticists,meteorologists,
managers,salespeople,programmers,techies,hardwareguys,
students,stockbrokers,administratorsofallkinds,librarians,
authors,bankers,artists—younameit.Perldoesnotexclude
anyone.Perlisforeveryoneanditrunsoneverything.
[1]UniversityofCalifornia,SantaCruz.

Nomatterwhoyouare,Ithinkyou'llagreethatapictureis
worthathousandwords,andsoisagoodexample.Perlby
ExampleisorganizedtoteachyouPerlfromscratchwith
examplesofcomplete,succinctprograms.Eachlineofascript
exampleisnumbered,andimportantlinesarehighlightedin
bold.Theoutputoftheprogramisthendisplayedwithline
numberscorrespondingtothescriptlinenumbers.Following

theoutputisaseparateexplanationforeachofthenumbered
lines.Theexamplesaresmallandtothepointforthetopicat
hand.Sincethebackboneofthisbookwasusedasastudent
guidetoaPerlcourse,thetopicsaremodularized.Eachchapter
buildsonthepreviousonewithaminimumofforward
referencingandalogicalprogressionfromonetopictothenext.
Thereareexercisesattheendofthechapters.Youwillfindall
oftheexamplesontheCDatthebackofthebook.Theyhave
beenthoroughlytestedonanumberofmajorplatforms.
PerlbyExampleisnotjustabeginner'sguidebutacomplete
guidetoPerl.ItcoversmanyaspectsofwhatPerlcando,from
regularexpressionhandling,toformattingreports,to
interprocesscommunication.ItwillteachyouaboutPerland,in
theprocess,alotaboutUNIXandWindows.SincePerlwas
originallywrittenonandforUNIXsystems,someUNIX
knowledgewillgreatlyaccelerateyourlearningcurve,butitis
notassumedthatyouarebyanymeansaguru.Anyone
reading,writing,orjustmaintainingPerlprogramscangreatly
profitfromthistext.
Perlhasarichvarietyoffunctionsforhandlingstrings,arrays,


thesysteminterface,networking,andmore.Inorderto
understandhowthesefunctionswork,backgroundinformation
concerningthehows,whys,andwhat-forsisprovidedbefore
demonstratingfunctionalsampleprograms.Thiseliminates
constinuallywadingthroughmanualpagesandotherbooksto
understandwhatisgoingon,whattheargumentsmean,and
whatthefunctionactuallydoes.
Theappendicescontainacompletelistoffunctionsand

definitions,command-lineswitches,specialvariables,popular
modules,andthePerldebugger;abioinformaticstutorialto
introduceBioPerl,andatutorialcoveringmod_perl,thefast
waytocreateserversidePerlscriptsthatreplacetheneedfor
theCommonGatewayInterface.
Ihavebeenteachingforthepastthirtyyearsandam
committedtounderstandinghowpeoplelearn.Havingtaught
Perlnowformorethan14years,allovertheworld,Ifindthat
manynewPerlersgetfrustratedwhentryingtoteach
themselveshowtoprogram.Mostpeopleseemtolearnbest
fromsuccinctlittleexamplesandpractice.SoIwroteabookto
helpmyselflearnandtohelpmystudents,andnowtohelp
you.AsPerlhasgrown,sohavemybooks.Thislatest,fourth,
editionincludesanewchapteronPerlandDBIwithMySQL,a
revisedchapteronPerlobjects,andnewexamplesand
explanationsfortherestofthechapterstokeepthingscurrent
andinteresting.Theappendixmaterialhasbeenrevisedto
includeBioPerlandmod_perl.Inthisbook,youwillnotonly
learnPerl,butalsosaveyourselfagreatdealoftime.Atleast
that'swhatmystudentsandreadershavetoldme.Youbethe
judge.


Acknowledgments
I'dliketoacknowledgethefollowingpeoplefortheir
contributionstothefourthedition.
ThankstoDmitriKorzhandTechneGroupfortheirskillin
editing,formatting,andindexingthatturnedmyattemptsat
usingFrameMakerfromaroughchunkofrawtextintoareal
professional,polishedbook.

I'dliketoacknowledgeOlegOrel,abrilliantstudentfrom
NetApp,whowrotetheinitialprogramtoillustrate"closures"in
thechapteronobjects,andwhohelpedmewiththeproblemsI
washavingdownloadingmodulesfromCPAN.
Thankyou,MarkTaub,theeditor-in-chieftobepraisedfor
beingverycoolineverystepoftheprocessfromthesigningof
thecontracttothefinalbookthatyouhavenowinyourhand.
Markhasawayofmakingsuchanarduoustaskseempossible;
hesofttalksimpossibledeadlines,keepsupasteadypressure,
anddoesn'tgetcrazyovermisseddeadlines,quietlyachieving
hisgoalandalwayswithasubtlesenseofhumor.Thankyou,
Mark,forbeingthedrivingforcebehindthisnewedition!
Ofcourse,noneofthiswouldhavebeenpossiblewithoutthe
contributionsofthePerlpioneers—LarryWall,RandalSchwartz,
andTomChristiansen.Theirbooksaremustreadingandinclude
LearningPerlbyRandalSchwartzandProgrammingPerlby
LarryWall,TomChristiansen,andJonOrwant.
Andlast,butcertainlynotleast,ahugethankstoallthe
students,worldwide,whohavedonealltherealtroubleshooting
andkeptthesubjectalive.


Chapter1.ThePracticalExtractionand
ReportLanguage

1.1.WhatIsPerl?
"Laziness,impatience,andhubris.GreatPerlprogrammers
embracethosevirtues."
—LarryWall
Perlisanall-purpose,opensource(freesoftware)interpreted

languagemaintainedandenhancedbyacoredevelopment
teamcalledthePerlPorters.Itisusedprimarilyasascripting
languageandrunsonanumberofplatforms.Althoughinititally
designedfortheUNIXoperatingsystem,Perlisrenownedforits
portabilityandnowcomesbundledwithmostoperating
systems,includingRedHatLinux,Solaris,FreeBSD,Macintosh,
andmore.Duetoitsversatility,Perlisoftenreferredtoasthe
SwissArmyknifeofprogramminglanguages.
LarryWallwrotethePerllanguagetomanagelogfilesand
reportsscatteredoverthenetwork.AccordingtoWikipedia.org,
"Perlwasoriginiallynamed"Pearl"afterthe"Parableofthe
Pearl"fromthe"GospelofMatthew."Theparableisbrief:A
merchantisseekingpearls.Hefindsonethatissovaluableand
beautifulthatheiswillingtoselleverythinghehastopurchase


it.Andintheendheisevenwealthierthanhewasbefore.
Howeveryouinterpretthis,ithasverypositiveimplications.

Beforeitsofficialreleasein1987the"a"in"Pearl"wasdropped
andthelanguagehassincebeencalled"Perl,"laterdubbedthe
PracticalExtractionandReportLanguage,andbysome,itis
referredtoasthePathologicallyEclecticRubbishLister.Perlis
reallymuchmorethanapracticalreportinglanguageoreclectic
rubbishlisterasyou'llsoonsee.Perlmakesprogrammingeasy,
flexible,andfast.Thosewhouseit,loveit.Andthosewhouse
itrangefromexperiencedprogrammerstonoviceswithlittle
computerbackgroundatall.Thenumberofuserscontinuesto
growataphenomenalrate.[1]
[1]Perlisspelled"Perl"whenreferringtothelanguage,and"perl"when


referringtotheinterpreter.

Perl'sheritageisUNIX.Perlscriptsarefunctionallysimilarto
UNIXawk,sed,shellscripts,andCprograms.Shellscripts
consistprimarilyofUNIXcommands;Perlscriptsdonot.
Whereassedandawkareusedtoeditandreportonfiles,Perl
doesnotrequireafileinordertofunction.WhereasChasnone
ofthepatternmatchingandwildcardmetacharactersofthe
shells,sed,andawk,Perlhasanextendedsetofcharacters.
Perlwasoriginallywrittentomanipulatetextinfiles,extract
datafromfiles,andwritereports,butthroughcontinued
development,itcanmanipulateprocesses,performnetworking
tasks,processWebpages,talktodatabases,andanalyze
scientificdata.PerlistrulytheSwissArmyknifeof
programminglanguages;thereisatoolforeveryone.


Theexamplesinthisbookwerecreatedonsystemsrunning
Solaris,Linux,MacintoshUNIX,andWin32.
Perlisoftenassociatedwithacamelsymbol,atrademarkof
O'ReillyMedia,whichpublishedthefirstbookonPerl,called
ProgrammingPerlbyLarryWallandRandalSchwartz,referred
toas"theCamelBook."


Chapter1.ThePracticalExtractionand
ReportLanguage

1.1.WhatIsPerl?

"Laziness,impatience,andhubris.GreatPerlprogrammers
embracethosevirtues."
—LarryWall
Perlisanall-purpose,opensource(freesoftware)interpreted
languagemaintainedandenhancedbyacoredevelopment
teamcalledthePerlPorters.Itisusedprimarilyasascripting
languageandrunsonanumberofplatforms.Althoughinititally
designedfortheUNIXoperatingsystem,Perlisrenownedforits
portabilityandnowcomesbundledwithmostoperating
systems,includingRedHatLinux,Solaris,FreeBSD,Macintosh,
andmore.Duetoitsversatility,Perlisoftenreferredtoasthe
SwissArmyknifeofprogramminglanguages.
LarryWallwrotethePerllanguagetomanagelogfilesand
reportsscatteredoverthenetwork.AccordingtoWikipedia.org,
"Perlwasoriginiallynamed"Pearl"afterthe"Parableofthe
Pearl"fromthe"GospelofMatthew."Theparableisbrief:A
merchantisseekingpearls.Hefindsonethatissovaluableand
beautifulthatheiswillingtoselleverythinghehastopurchase


×