Tải bản đầy đủ (.pdf) (839 trang)

Sams teach yourself perl in 24 hours 3rd edition jun 2005 ISBN 0672327937

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 (4.81 MB, 839 trang )

SAMSTeachYourselfPerlin24Hours
THIRDEDITION
ByClintonPierce
...............................................
Publisher:SamsPublishing
PubDate:June15,2005
ISBN:0-672-32793-7
Pages:480

TableofContents|Index

LearnPerlprogrammingquicklyandeasilywith24one-hourlessonsinSamsTeach
YourselfPerlin24Hours,3/e.Thesestep-by-steplessonswillteachyouthebasicsof
Perlandhowtoapplyitinwebdevelopmentandsystemadministration.Plus,the
thirdeditionhasbeenupdatedtoinclude5chaptersonnewtechnologies,information
onthelatestversionofPerlandalookaheadtoPerl6.Youwillfocusonreal-world
development,includinghowto:
EffectivelyusePerlforlargedevelopmentprojectsusingPerlModules.
UsePerlfordataprocessing.
UtilizePerlasa"glue"languagewithotherprogramminglanguages.
UsePerlasawebdevelopmentlanguage.
Theconcise,modularformatoftheSamsTeachYourselfPerlin24Hours,3/eisthe
idealwaytolearnfortoday'sworkingprofessional.


SAMSTeachYourselfPerlin24Hours
THIRDEDITION
ByClintonPierce
...............................................
Publisher:SamsPublishing
PubDate:June15,2005


ISBN:0-672-32793-7
Pages:480

TableofContents|Index



Copyright



AbouttheAuthor



Acknowledgments



WeWanttoHearfromYou!



ReaderServices



Introduction







HowtoUseThisBook
ConventionsUsedinThisBook
PartI.PerlFundamentals
Hour1.GettingStartedwithPerl



InstallingPerl



Documentation



YourFirstProgram



Summary



Q&A





Workshop
Hour2.Perl'sBuildingBlocks:NumbersandStrings



Literals



ScalarVariables



ExpressionsandOperators



MoreOperators



Exercise:InterestCalculator



Summary




Q&A



Workshop



Hour3.ControllingtheProgram'sFlow



Blocks



TheifStatement




Looping



OtherFlowControlTools




Exercise:FindingPrimes



Summary



Q&A



Workshop



Hour4.StackingBuildingBlocks:ListsandArrays



PuttingThingsintoListsandArrays



GettingElementsOutofanArray



ManipulatingArrays




Exercise:PlayingaLittleGame



Summary



Q&A



Workshop



Hour5.WorkingwithFiles



OpeningFiles



Reading




Writing



FreeFiles,TestingFiles,andBinaryData



Summary



Q&A



Workshop



Hour6.PatternMatching



SimplePatterns



TheMetacharacters




Substitution



Exercise:CleaningUpInputData



PatternMatchingOddsandEnds



Summary



Q&A



Workshop



Hour7.Hashes




FillingYourHash



GettingDataOutofaHash



ListsandHashes



HashOddsandEnds



UsefulThingstoDowithaHash



Exercise:CreatingaSimpleCustomerDatabasewithPerl



Summary



Q&A




Workshop



Hour8.Functions



CreatingandCallingSubroutines



Scope



Exercise:Statistics




FunctionFootnotes



Summary




Q&A



Workshop




PartII.AdvancedFeatures
Hour9.MoreFunctionsandOperators



SearchingScalars



Transliteration,NotSubstitution



ABetterWaytoprint



Exercise:AFormattedReport




NewWayswithArrays



Summary



Q&A



Workshop



Hour10.FilesandDirectories



GettingaDirectoryListing



Exercise:TheUnixgrep



Directories




UnixStuff



EverythingYouEverWantedtoKnowAboutTHATFile



Exercise:RenamingFilesEnMasse



Summary



Q&A



Workshop



Hour11.SystemInteraction




Thesystem()Function



CapturingOutput



Pipes



FirstLessoninPortability



Summary



Q&A



Workshop



Hour12.UsingPerl'sCommand-LineTools




WhatIstheDebugger?



Exercise:FindingtheBug



OtherCommand-LineStuff



Summary



Q&A



Workshop



Hour13.ReferencesandStructures




ReferenceBasics



RecipesforStructures



Exercise:AnotherGame,Maze



Summary



Q&A




Workshop



Hour14.UsingModules




AGentleIntroduction



AQuickTour



FullListofStandardModules



Summary



Q&A




Workshop
Hour15.FindingPermanence



DBMFiles




Exercise:AFree-FormMemoPad



TextFilesasDatabases



RandomFileAccess



Locking



Summary



Q&A



Workshop



Hour16.ThePerlCommunity




What'sPerlAllAbout,Anyway?



TheComprehensivePerlArchiveNetwork(CPAN)



YourNextSteps



OtherResources



Summary



Q&A





Workshop
PartIII.ApplyingPerl

Hour17.WritingModules



BuildingaModule



ScopingRevisited



Anotherstatement:our



Example:AModuletoHandleCommonFileInformationRequests



Summary



Q&A



Workshop




Hour18.ObjectPrimer



Classes,Properties,andMethods



Example:ImplementationofCarinPerl



Example:FileInformationClass



Summary



Q&A



Workshop




Hour19.DataProcessing



HowtoLookatData



DealingwithTableData



XMLData




Summary



Q&A




Workshop
Hour20.PerlasaGlueLanguage




WeatherStation



PresentingDataasPDF



ReadingandWritingExcelSpreadsheets



Summary



Q&A




Workshop
Hour21.IntroductiontoCGI



BrowsingtheWeb




Don'tSkipThisSection



YourFirstCGIProgram



WhattoDoWhenYourCGIProgramDoesn'tWork



Summary



Q&A



Workshop



Hour22.BasicForms



HowFormsWork




PassingInformationtoYourCGIProgram



WebSecurity101



AGuestbook



Summary



Q&A



Workshop



Hour23.ComplexForms




TheStatelessWeb



HiddenFields



AMultipageSurvey



Summary



Q&A




Workshop
Hour24.ManipulatingHTTPandCookies



TheHTTPConversation




MoreDetailsonCallingCGIPrograms



Cookies



LongTermCookies



ProblemswithCookies



Summary



Q&A



Workshop






PartIV.Appendixes
AppendixA.InstallingModules
PickingtheRightModule




InstallingtheModulesUnder…



WhattoDoWhenYou'reNotAllowedtoInstallModules



Index


Copyright
Copyright©2005bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,storedinaretrieval
system,ortransmittedbyanymeans,electronic,mechanical,photocopying,
recording,orotherwise,withoutwrittenpermissionfromthepublisher.No
patentliabilityisassumedwithrespecttotheuseoftheinformationcontained
herein.Althougheveryprecautionhasbeentakeninthepreparationofthisbook,
thepublisherandauthorassumenoresponsibilityforerrorsoromissions.Noris
anyliabilityassumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2004195543

PrintedintheUnitedStatesofAmerica
FirstPrinting:June2005
080706054321

Trademarks
Alltermsmentionedinthisbookthatareknowntobetrademarksorservice
markshavebeenappropriatelycapitalized.SamsPublishingcannotattesttothe
accuracyofthisinformation.Useofaterminthisbookshouldnotberegarded
asaffectingthevalidityofanytrademarkorservicemark.

WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteandasaccurateas
possible,butnowarrantyorfitnessisimplied.Theinformationprovidedisonan
"asis"basis.Theauthorandthepublishershallhaveneitherliabilitynor
responsibilitytoanypersonorentitywithrespecttoanylossordamagesarising


fromtheinformationcontainedinthisbook.

BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhenorderedin
quantityforbulkpurchasesorspecialsales.Formoreinformation,please
contact
U.S.CorporateandGovernmentSales
1-800-382-3419

ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales



Credits
SeniorEditor
ScottMeyers
ManagingEditor
CharlotteClapp
ProjectEditor
AndyBeaster
CopyEditor
KateGivens
Indexer


ChrisBarrick
Proofreader
HeatherArle
TechnicalEditor
AndyLester
PublishingCoordinator
VanessaEvans
BookDesigner
GaryAdair
PageLayout
KellyMaish

Dedication
ToHeidiandCalvin,fornotkillingmethissummerandsupportingmeduring
thisadventure.Withoutyoursupport,I'dhavelostevenmoreofmymarbles.


AbouttheAuthor

ClintonPierceisasoftwareengineer,freelanceprogrammer,andinstructor.He
hasbeenansweringquestionsaboutPerlonUSENETformanyyearsandhas
beenwritingcoursewareandteachingPerltohisco-workersandanyoneelse
whowilllistenforaboutaslong.Heisasoftwareengineerforapayroll
company,who,whennotdesigningmiddlewaresoftwaretointegratelegacy
systemstotheWeb,navigatingtheintricaciesofpayrolltaxes,teachingUNIX
andPerl,writingbooksandarticles,orwritingprogramsathomeJustForThe
FunOfIt,harborssecretdreamsofbeingabductedbywoodnymphsandliving
inthedeepforestwithouttechnology.YoucanvisithisWebsiteat
forupdatesandcorrections,orjusttosayhello.


Acknowledgments
"IfIhaveseenfurther,itisbystandingontheshouldersofGiants"Isaac
Newton.
AnybookonPerlshouldfirstrecognizetheGiantwhogaveusPerlinthefirst
place.Thanks,Larry.
InotonlystoodontheshouldersofGiants,butalsowasledbyhoardsofothers.
Tomakesurethisbookcameoutaserror-freeaspossible,Iinvitedperfect
strangerstowatch,criticize,andcorrectmewhennecessary.Thishasbeena
humblingexperience.Innoparticularorder,thepeoplewhoannoyedmethe
mostandwhodeservethemostthanksareAbigail,GregBacon,SeanBurke,
KenFox,KevinMeltzer,TomPhoenix,andRandalSchwartz.Also,thanksto
MichaelSchwern,TomGrydeland,MattBielanski,MarkJason-Dominus,Jeff
Pinyan,GaryRoss,AndrewChen,andJohnBellforfindingbugsandoffering
suggestions.Overtheyearshelpfulreadershavebeeninstrumentalinweeding
outsmallproblemswiththetextandhelpingwiththeexplanations,notably:Lisa
M,RobertB,QinglinL,IhorP,DavidK,DanG,andLauraC.
Somesmallcreditshouldalsogoto#perlforlettingmesoundmyideasoffthem
andforgivingmetheirhonestandsometimesbrutalopinions.

SomewhatresponsibleforthisbookareBillCrawfordandDonnaHinklefor
gettingmeintothiswholetrainingmessinthefirstplace.Thanks,Ithink.
Ofcourse,I'dliketothankthepeopleatSamsPublishingwhoputupwithanew
authorandallthepainandagonythatgoeswiththeterritory.Withoutpeople
likeRandiRoger,ScottMeyers,KateGivens,andeveryonebehindthescenes
thatIdidn'tgettotalktobutwhoarejustasimportant,I'dneverhaveput
togetheranythinglikethis.


WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcriticandcommentator.
Wevalueyouropinionandwanttoknowwhatwe'redoingright,whatwecould
dobetter,whatareasyou'dliketoseeuspublishin,andanyotherwordsof
wisdomyou'rewillingtopassourway.
Youcanemailorwritemedirectlytoletmeknowwhatyoudidordidn'tlike
aboutthisbookaswellaswhatwecandotomakeourbooksstronger.
PleasenotethatIcannothelpyouwithtechnicalproblemsrelatedtothetopicof
thisbook,andthatduetothehighvolumeofmailIreceive,Imightnotbeable
toreplytoeverymessage.
Whenyouwrite,pleasebesuretoincludethisbook'stitleandauthoraswellas
yournameandphoneoremailaddress.Iwillcarefullyreviewyourcomments
andsharethemwiththeauthorandeditorswhoworkedonthebook.

E-mail:



Mail:

MarkTaber

AssociatePublisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA


ReaderServices
FormoreinformationaboutthisbookoranotherSamstitle,visitourwebsiteat
www.samspublishing.com.TypetheISBN(excludinghyphens)orthetitleofa
bookintheSearchfieldtofindthepageyou'relookingfor.


Introduction
"Anysufficientlyadvancedtechnologyisvirtuallyindistinguishablefrom
magic."
ArthurC.Clarke
Rememberthiswell:There'snothingmagicalaboutprogrammingacomputer.
Likeanythingthatseemsmagical,there'salwaysatricktoitandprogrammingis
nodifferent.Allyouneedaresomeanalyticalthinkingskills,thedesiretolearn,
andsometimetolearnPerl.Thebestwaytolearnhowtoprogramacomputeror
anytaskreallyistohaveagoal.YourgoalcouldbetospiceupyourWebpages,
convertaprogramyoualreadyhavetoPerl,ortosatisfyidlecuriosityitdoesn't
reallymatter.
Now,giventhatyou'veestablishedagoalandhavesomethinkingskills,what
doesthisbookhaveforyou?
ThisbookwillteachyouthebasicsofthePerlprogramminglanguage.You'll
learnjustenoughPerltodosomethinguseful.Youwillnotbeoverwhelmedwith
detailsthat,althoughinteresting,willonlygetinyourwayandthatyou'll
probablyneveruseagain.Eachnewconceptinthisbookisdemonstratedbylots
ofworkingcodeexamples.Goaheadflipthroughthebookandsee.

ButwhyPerl?Almosteverycompanythatusesprogrammingofsomekinduses
Perl.Perlisfoundinfinance,manufacturing,genetics,themilitary,andevery
otherapplicationknowntohumankind.And,ofcourse,Perlisusedonthe
InternetandtheWorldWideWeb.Perlisn'tgoingawayanytimesoon,whichis
whylearningitisaninvestmentinyourtimethatwillpayoffforyearstocome.
It'salsopossibletocreatereallystunningPerlprogramswithjustasmallbitof
code.UsingalittlebitofPerltogluetogetherotherapplications,languages,and
technologies,you'llbecreatingusefulPerlprogramsinnotime.


HowtoUseThisBook
Thisbookisdividedinto24segmentsthattakeroughlyanhourtocomplete.
Youcanworkthroughthelessonsinthespaceofaday(ifyoudon'tplantoeat
orsleep),oryoucantakeyourtimeandworkthroughthehourlessonsatyour
ownpace.
Attheendofeachhour,you'llbeabletoaccomplishanewsetoftasks.The
lessonscontainclearexplanationsofthelanguagefeaturesandhowtheywork.
Inaddition,eachhourprovidesyouwiththeopportunityforhands-ontraining,
simplybyfollowingthestepsdescribed.


ConventionsUsedinThisBook
SamsTeachYourselfPerlin24Hoursusesanumberofconventionsthatare
consistentthroughoutthisbook:
Eachhourbeginswithanoverviewofwhatyouwilllearn.
Step-by-stepinstructionsareprecededbyaToDoicon.
Everyhourendswithasummaryandaseriesofcommonlyaskedquestions
andanswers;hopefully,you'llfindtheanswerstoyourquestionsamong
them.
Inaddition,theseelementsappearthroughoutthebook:

BytheWay
Notesprovideyouwithcommentsandasidesaboutthetopicathand.

DidyouKnow?
Tipsoffershortcutsandhintsongettingthetaskdone.

WatchOut!
Cautionsexplainroadblocksyoumightencounterwhenyouwork
withPerlandtellyouhowtoavoidthem.


Newtermsareemphasizedbybeingplacedinboldforyoureasyreference.


PartI:PerlFundamentals


HOUR1GettingStartedwithPerl



HOUR2Perl'sBuildingBlocks:NumbersandStrings



HOUR3ControllingtheProgram'sFlow



HOUR4StackingBuildingBlocks:ListsandArrays




HOUR5WorkingwithFiles



HOUR6PatternMatching



HOUR7Hashes



HOUR8Functions


Hour1.GettingStartedwithPerl
WhatYou'llLearninThisHour
InstallingPerl
AccessingPerl'sinternaldocumentation
WritingyourfirstPerlscript
Perlisageneral-purposeprogramminglanguage.Itcanbeusedforanythingthat
anyotherprogramminglanguagecanbeusedfor.Ithasbeenusedinevery
industryimaginableforalmostanytaskyoucanthinkof.It'susedonthestock
market;inmanufacturing,design,bioinformatics,customersupport,quality
control,systemsprogramming,payroll,andinventory;and,ofcourse,onthe
Web.
PerlisusedinsomanyplacesbecausePerlisagluelanguage.Agluelanguage

isusedtobindthingstogether.Youprobablywouldn'twanttowriteaword
processorinPerlalthoughyoucouldbecausegoodwordprocessorsarealready
available.Writingadatabase,aspreadsheet,anoperatingsystem,orafullfeaturedWebserverinPerlwouldbesillybutagain,possible.
WhatPerlisgoodatistyingtheseelementstogether.Perlcantakeyour
database,convertitintoaspreadsheet-readyfile,and,duringtheprocessing,fix
thedataifyouwant.Perlcanalsotakeyourwordprocessingdocumentsand
convertthemtoHTMLfordisplayontheWeb.
Asasideeffectofbeingalanguagedesignedtoglueelementstogether,Perlis
veryadaptable.Itrunsunder,atlastcount,abouttwodozenoperating
systemsandprobablymore.Perl'sprogrammingstyleisveryflexible,soyoucan
dothesamethingsinmanyways.YourPerlprogramsmaylooknothinglike
mine,butiftheybothwork,that'sokay.Perlcanbeastrictlanguagewhenit
needstobe,butitcanalsobeforgivingtonewsprogrammersifyouwant.It'sall
uptoyou.


Letmejustclearupafewpoints.Thenameoftheprogramminglanguageis
Perl.Thenameoftheprogramthatrunsyourprograms,theinterpreter,isperl.
Thedistinctionusuallyisn'tveryimportanttoyouexceptwhenyou'retryingto
startyourprograms;thenit'salwaysperl.Sometimesbutnothereyouwillsee
PerlwrittenasPERL,probablybecauseoneexplanationofPerl'snameisasan
acronymforPracticalExtractionandReportLanguage.Nobodyeverreally
calleditPERL;it'stoopretentious.It'sjustPerltoitsfriends.
BytheWay
ManyofPerl'sfeatureswere"borrowed"fromotherlanguages.This
borrowinggaverise,earlyon,toPerl'sotheracronym-expansion:
PathologicallyEclecticRubbishLister.


InstallingPerl

ToplaywithPerl,youfirsthavetoinstallit.Perl'sinstallationisdesignedtobe
easyanderrorfree.Infact,aspartoftheinstallationsteps,Perlshoulddoaselftesttomakesurethatit'sokay.Theinstallationproceduresvarywidely
dependingonwhatoperatingsystemyouhave.So,togetthingsmoving,pick
whichoperatingsystemyouhavefromthesectionshere,andfollowalong.

Stop!Wait!MaybeYouAlreadyHavePerl
BeforeyougothroughallthetroubletoinstallPerlonyoursystem,youshould
checktoseewhetheryoualreadyhaveit.SomeUnixvendorsshipPerlwiththe
operatingsystem.WindowsNTcomeswithPerlaspartoftheWindowsNT
ResourceKit(butthatversionisabitold).ToseewhetheryouhavePerl
properlyinstalledonyouroperatingsystem,youneedtogettoacommand
prompt.
UnderUnix,simplylogintothesystem.Ifyouhaveagraphicalenvironment,
youneedtoopenaterminalwindow.Afteryou'veloggedinoropenedyour
window,youmayseeapromptlikethis:
$

Itmightbea%oritmightlooklikebash%,buteitherway,itiscalledtheshell
promptorcommandprompt.Forthefirstfewhours,you'llneedtobeatthis
prompttointeractwithPerl.
ToseewhetherPerlisproperlyinstalledonyoursystem,typethefollowing(but
notthe$prompt):


$perl-v

Eitherthesystemrespondswithanerrormessagesuchascommandnot
found,orPerlrespondsandprintsitsversionnumber.IfPerlprintsitsversion
number,it'sinstalled.Youprobablydonothavetoreinstallit.
WatchOut!

Theversionnumberreportedshouldbeatleast5perhaps5.004,
5.005,5.6,5.8,andsoonbutnolower.IfPerlrespondswithaversion
of4.x,youmustinstallanewcopy.Perlversion4isold,buggy,and
nolongermaintained;fewoftheexamplesinthisbookwillwork
withPerlversion4.Atthetimeofthiswriting,5.8.6isconsideredthe
currentversionofPerl.

ToseewhetherPerlisproperlyinstalledonaWindowsmachineyouneedtoget
toanMS-DOSprompt,similartoFigure1.1.
Figure1.1.YoucancheckyourversionofPerlatthisDOSprompt.
[Viewfullsizeimage]


Atthatprompt,typethefollowing(butdon'trepeattheprompt):
C:\>perl-v

IfPerlisproperlyinstalled,itanswerswithitsversionnumber.Asnotedinthe
previouscaution,itshouldbeatleastversion5.IfMS-DOSreplieswithBad
commandorfilename,youneedtoinstallPerlproperly.
OntheMacintosh(runningMacOS),youcanchecktoseewhetherPerlis
installedbyrunningFileFind(Command-f)for'MacPerl'asshowninFigure
1.2.Iftheapplicationisfound,openitandlookatthe"AboutMacPerl"option
undertheApplemenu.YoushouldhaveatleastVersion5.2.0Patchlevel5.004;
otherwise,youshouldinstallanewversionofMacPerl.


Figure1.2.LookingforPerlontheMacintosh.

NewerMacintoshsystemsrunMacOSX.Underneaththepoint-and-click
interface,thereisaUnixoperatingsystem.Togetashellprompt(sothatyoucan

followtheUnixinstructions)gotoFinder,Applications,Utilitiesandselect
Terminal.YoushouldseeawindowsimilartoFigure1.3.
Figure1.3.MacOSXTerminal,withPerlversionoutput.

GenerallyforMacOSX,followtheUnixinstructionsinthisbook.Thereare
extensionsparticulartoMacOSXthatyoucandownloadfromCPAN.


×