Tải bản đầy đủ (.pdf) (1,106 trang)

OReilly perl best practices jul 2005 ISBN 0596001738

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 (2.56 MB, 1,106 trang )

PerlBestPractices
ByDamianConway
...............................................
Publisher:O'Reilly
PubDate:July2005
ISBN:0-596-00173-8
Pages:542

TableofContents|Index

Manyprogrammerscodebyinstinct,relyingonconvenienthabitsora
"style"theypickedupearlyon.Theyaren'tconsciousofallthe
choicestheymake,likehowtheyformattheirsource,thenamestheyuse
forvariables,orthekindsofloopstheyuse.They'refocusedentirely
onproblemsthey'resolving,solutionsthey'recreating,andalgorithms
they'reimplementing.Sotheywritecodeinthewaythatseemsnatural,
thathappensintuitively,andthatfeelsgood.
Butifyou'reseriousaboutyourprofession,intuitionisn'tenough.
PerlBestPracticesauthorDamianConwayexplainsthatrules,
conventions,standards,andpracticesnotonlyhelpprogrammers
communicateandcoordinatewithoneanother,theyalsoprovidea
reliableframeworkforthinkingaboutproblems,andacommonlanguage
forexpressingsolutions.ThisisespeciallycriticalinPerl,because
thelanguageisdesignedtooffermanywaystoaccomplishthesametask,
andconsequentlyitsupportsmanyincompatibledialects.
WithagooddoseofAussiehumor,Dr.Conway(familiartomanyinthe
Perlcommunity)offers256guidelinesontheartofcodingtohelpyou
writebetterPerlcode--infact,thebestPerlcodeyoupossiblycan.
Theguidelinescovercodelayout,namingconventions,choiceofdataand
controlstructures,programdecomposition,interfacedesignand
implementation,modularity,objectorientation,errorhandling,testing,


anddebugging.
They'redesignedtoworktogethertoproducecodethatisclear,robust,
efficient,maintainable,andconcise,butDr.Conwaydoesn'tpretend
thatthisistheonetrueuniversalandunequivocalsetofbest
practices.Instead,PerlBestPracticesofferscoherentandwidely
applicablesuggestionsbasedonreal-worldexperienceofhowcodeis
actuallywritten,ratherthanonsomeone'sivory-towertheoriesonhow
softwareoughttobecreated.


Mostofall,PerlBestPracticesoffersguidelinesthatactuallywork,
andthatmanydevelopersaroundtheworldarealreadyusing.Muchlike
Perlitself,theseguidelinesareabouthelpingyoutogetyourjob
done,withoutgettingintheway.
PraiseforPerlBestPracticesfromPerlcommunitymembers:

"AsamanagerofalargePerlproject,I'densurethateverymemberofmyteamhasa
copyofPerlBestPracticesontheirdesk,anduseitasthebasisforanin-housestyle
guide."--RandalSchwartz
"TherearenomoreexcusesforwritingbadPerlprograms.AlllevelsofPerlprogrammer
willbemoreproductiveafterreadingthisbook."--PeterScott
"PerlBestPracticeswillbethenextbigimportantbookintheevolutionofPerl.Theideas
andpracticesDamianlaysdownwillhelpbringPerloutfromundertheembarrassing
headingof"scriptinglanguages".ManyofushaveknownPerlisarealprogramming
language,worthyofallthetasksnormallydelegatedtoJavaandC++.WithPerlBest
Practices,Damianshowsspecificallyhowandwhy,soeveryoneelsecansee,too."--Andy
Lester
"Damian'sdonewhatmanythoughtimpossible:showhowtobuildlarge,maintainablePerl
applications,whilestilllettingPerlbethepowerful,expressivelanguagethatprogrammers
havelovedforyears."--BillOdom

"Finally,ameanstobringlastingordertotheprocessandproductofrealPerl
developmentteams."--AndrewSundstrom
"PerlBestPracticesprovidesavaluableeducationinhowtowriterobust,maintainable
Perl,andisadefinitivecitationsourcewhencoachingotherprogrammers."--Bennett
Todd
"I'vebeenteachingPerlforyears,andfindthesamequestionkeepsbeingasked:Where
canIfindareferenceforwritingreusable,maintainablePerlcode?FinallyIhaveadecent
answer."--PaulFenwick
"Atlastawellresearched,wellthought-out,comprehensiveguidetoPerlstyle.Insteadof
eachofusdevelopingourown,wecanlearngoodpracticesfromoneofPerl'smostprolific
andexperiencedauthors.Irecommendthisbooktoanyonewhoprefersgettingonwith
thejobratherthangoingbackandfixingerrorscausedbysyntaxandpoorstyleissues."-JacintaRichardson
"Ifyoucareaboutprogramminginanylanguagereadthisbook.Evenifyoudon'tintend
tofollowallofthepractices,thinkingthroughyourstylewillimproveit."--Steven
Lembark
"ThePerlcommunity'sbestauthorisbackwithanotheroutstandingbook.Therehasnever
beenacomprehensivereferenceonhighqualityPerlcodingandstyleuntilPerlBest
Practices.ThisbookfillsalargegapineveryPerlbookshelf."--UriGuttman


PerlBestPractices
ByDamianConway
...............................................
Publisher:O'Reilly
PubDate:July2005
ISBN:0-596-00173-8
Pages:542

TableofContents|Index


















































Copyright
Dedication
Preface
ContentsofThisBook
ConventionsUsedinThisBook
CodeExamples
Feedback
Acknowledgments
Chapter1.BestPractices
Section1.1.ThreeGoals
Section1.2.ThisBook
Section1.3.Rehabiting
Chapter2.CodeLayout

Section2.1.Bracketing
Section2.2.Keywords
Section2.3.SubroutinesandVariables
Section2.4.Builtins
Section2.5.KeysandIndices
Section2.6.Operators
Section2.7.Semicolons
Section2.8.Commas
Section2.9.LineLengths
Section2.10.Indentation
Section2.11.Tabs
Section2.12.Blocks



















































































Section2.13.Chunking
Section2.14.Elses
Section2.15.VerticalAlignment
Section2.16.BreakingLongLines
Section2.17.Non-TerminalExpressions
Section2.18.BreakingbyPrecedence
Section2.19.Assignments
Section2.20.Ternaries
Section2.21.Lists
Section2.22.AutomatedLayout
Chapter3.NamingConventions
Section3.1.Identifiers
Section3.2.Booleans
Section3.3.ReferenceVariables
Section3.4.ArraysandHashes
Section3.5.Underscores
Section3.6.Capitalization
Section3.7.Abbreviations
Section3.8.AmbiguousAbbreviations
Section3.9.AmbiguousNames
Section3.10.UtilitySubroutines
Chapter4.ValuesandExpressions
Section4.1.StringDelimiters
Section4.2.EmptyStrings
Section4.3.Single-CharacterStrings
Section4.4.EscapedCharacters
Section4.5.Constants
Section4.6.LeadingZeros

Section4.7.LongNumbers
Section4.8.MultilineStrings
Section4.9.HereDocuments
Section4.10.HeredocIndentation
Section4.11.HeredocTerminators
Section4.12.HeredocQuoters
Section4.13.Barewords
Section4.14.FatCommas
Section4.15.ThinCommas
Section4.16.Low-PrecedenceOperators
Section4.17.Lists


















































































Section4.18.ListMembership
Chapter5.Variables
Section5.1.LexicalVariables
Section5.2.PackageVariables
Section5.3.Localization
Section5.4.Initialization
Section5.5.PunctuationVariables
Section5.6.LocalizingPunctuationVariables
Section5.7.MatchVariables
Section5.8.Dollar-Underscore
Section5.9.ArrayIndices
Section5.10.Slicing
Section5.11.SliceLayout
Section5.12.SliceFactoring
Chapter6.ControlStructures
Section6.1.IfBlocks
Section6.2.PostfixSelectors
Section6.3.OtherPostfixModifiers
Section6.4.NegativeControlStatements
Section6.5.C-StyleLoops
Section6.6.UnnecessarySubscripting
Section6.7.NecessarySubscripting
Section6.8.IteratorVariables
Section6.9.Non-LexicalLoopIterators
Section6.10.ListGeneration
Section6.11.ListSelections
Section6.12.ListTransformation
Section6.13.ComplexMappings
Section6.14.ListProcessingSideEffects
Section6.15.MultipartSelections

Section6.16.ValueSwitches
Section6.17.TabularTernaries
Section6.18.do-whileLoops
Section6.19.LinearCoding
Section6.20.DistributedControl
Section6.21.Redoing
Section6.22.LoopLabels
Chapter7.Documentation
Section7.1.TypesofDocumentation


















































































Section7.2.Boilerplates

Section7.3.ExtendedBoilerplates
Section7.4.Location
Section7.5.Contiguity
Section7.6.Position
Section7.7.TechnicalDocumentation
Section7.8.Comments
Section7.9.AlgorithmicDocumentation
Section7.10.ElucidatingDocumentation
Section7.11.DefensiveDocumentation
Section7.12.IndicativeDocumentation
Section7.13.DiscursiveDocumentation
Section7.14.Proofreading
Chapter8.Built-inFunctions
Section8.1.Sorting
Section8.2.ReversingLists
Section8.3.ReversingScalars
Section8.4.Fixed-WidthData
Section8.5.SeparatedData
Section8.6.Variable-WidthData
Section8.7.StringEvaluations
Section8.8.AutomatingSorts
Section8.9.Substrings
Section8.10.HashValues
Section8.11.Globbing
Section8.12.Sleeping
Section8.13.MappingandGrepping
Section8.14.Utilities
Chapter9.Subroutines
Section9.1.CallSyntax
Section9.2.Homonyms

Section9.3.ArgumentLists
Section9.4.NamedArguments
Section9.5.MissingArguments
Section9.6.DefaultArgumentValues
Section9.7.ScalarReturnValues
Section9.8.ContextualReturnValues
Section9.9.Multi-ContextualReturnValues
Section9.10.Prototypes

















































































Section9.11.ImplicitReturns
Section9.12.ReturningFailure
Chapter10.I/O

Section10.1.Filehandles
Section10.2.IndirectFilehandles
Section10.3.LocalizingFilehandles
Section10.4.OpeningCleanly
Section10.5.ErrorChecking
Section10.6.Cleanup
Section10.7.InputLoops
Section10.8.Line-BasedInput
Section10.9.SimpleSlurping
Section10.10.PowerSlurping
Section10.11.StandardInput
Section10.12.PrintingtoFilehandles
Section10.13.SimplePrompting
Section10.14.Interactivity
Section10.15.PowerPrompting
Section10.16.ProgressIndicators
Section10.17.AutomaticProgressIndicators
Section10.18.Autoflushing
Chapter11.References
Section11.1.Dereferencing
Section11.2.BracedReferences
Section11.3.SymbolicReferences
Section11.4.CyclicReferences
Chapter12.RegularExpressions
Section12.1.ExtendedFormatting
Section12.2.LineBoundaries
Section12.3.StringBoundaries
Section12.4.EndofString
Section12.5.MatchingAnything
Section12.6.LazyFlags

Section12.7.BraceDelimiters
Section12.8.OtherDelimiters
Section12.9.Metacharacters
Section12.10.NamedCharacters
Section12.11.Properties
Section12.12.Whitespace

















































































Section12.13.UnconstrainedRepetitions
Section12.14.CapturingParentheses
Section12.15.CapturedValues
Section12.16.CaptureVariables
Section12.17.PiecewiseMatching

Section12.18.TabularRegexes
Section12.19.ConstructingRegexes
Section12.20.CannedRegexes
Section12.21.Alternations
Section12.22.FactoringAlternations
Section12.23.Backtracking
Section12.24.StringComparisons
Chapter13.ErrorHandling
Section13.1.Exceptions
Section13.2.BuiltinFailures
Section13.3.ContextualFailure
Section13.4.SystemicFailure
Section13.5.RecoverableFailure
Section13.6.ReportingFailure
Section13.7.ErrorMessages
Section13.8.DocumentingErrors
Section13.9.OOExceptions
Section13.10.VolatileErrorMessages
Section13.11.ExceptionHierarchies
Section13.12.ProcessingExceptions
Section13.13.ExceptionClasses
Section13.14.UnpackingExceptions
Chapter14.Command-LineProcessing
Section14.1.Command-LineStructure
Section14.2.Command-LineConventions
Section14.3.Meta-options
Section14.4.In-situArguments
Section14.5.Command-LineProcessing
Section14.6.InterfaceConsistency
Section14.7.InterapplicationConsistency

Chapter15.Objects
Section15.1.UsingOO
Section15.2.Criteria
Section15.3.Pseudohashes

















































































Section15.4.RestrictedHashes
Section15.5.Encapsulation
Section15.6.Constructors
Section15.7.Cloning
Section15.8.Destructors
Section15.9.Methods
Section15.10.Accessors

Section15.11.LvalueAccessors
Section15.12.IndirectObjects
Section15.13.ClassInterfaces
Section15.14.OperatorOverloading
Section15.15.Coercions
Chapter16.ClassHierarchies
Section16.1.Inheritance
Section16.2.Objects
Section16.3.BlessingObjects
Section16.4.ConstructorArguments
Section16.5.BaseClassInitialization
Section16.6.ConstructionandDestruction
Section16.7.AutomatingClassHierarchies
Section16.8.AttributeDemolition
Section16.9.AttributeBuilding
Section16.10.Coercions
Section16.11.CumulativeMethods
Section16.12.Autoloading
Chapter17.Modules
Section17.1.Interfaces
Section17.2.Refactoring
Section17.3.VersionNumbers
Section17.4.VersionRequirements
Section17.5.Exporting
Section17.6.DeclarativeExporting
Section17.7.InterfaceVariables
Section17.8.CreatingModules
Section17.9.TheStandardLibrary
Section17.10.CPAN
Chapter18.TestingandDebugging

Section18.1.TestCases
Section18.2.ModularTesting


















































































Section18.3.TestSuites
Section18.4.Failure
Section18.5.WhattoTest
Section18.6.DebuggingandTesting
Section18.7.Strictures
Section18.8.Warnings
Section18.9.Correctness
Section18.10.OverridingStrictures

Section18.11.TheDebugger
Section18.12.ManualDebugging
Section18.13.Semi-AutomaticDebugging
Chapter19.Miscellanea
Section19.1.RevisionControl
Section19.2.OtherLanguages
Section19.3.ConfigurationFiles
Section19.4.Formats
Section19.5.Ties
Section19.6.Cleverness
Section19.7.EncapsulatedCleverness
Section19.8.Benchmarking
Section19.9.Memory
Section19.10.Caching
Section19.11.Memoization
Section19.12.CachingforOptimization
Section19.13.Profiling
Section19.14.Enbugging
AppendixA.EssentialPerlBestPractices
AppendixB.PerlBestPractices
SectionB.1.Chapter2,CodeLayout
SectionB.2.Chapter3,NamingConventions
SectionB.3.Chapter4,ValuesandExpressions
SectionB.4.Chapter5,Variables
SectionB.5.Chapter6,ControlStructures
SectionB.6.Chapter7,Documentation
SectionB.7.Chapter8,Built-inFunctions
SectionB.8.Chapter9,Subroutines
SectionB.9.Chapter10,I/O
SectionB.10.Chapter11,References

SectionB.11.Chapter12,RegularExpressions













































SectionB.12.Chapter13,ErrorHandling
SectionB.13.Chapter14,Command-LineProcessing
SectionB.14.Chapter15,Objects
SectionB.15.Chapter16,ClassHierarchies
SectionB.16.Chapter17,Modules
SectionB.17.Chapter18,TestingandDebugging
SectionB.18.Chapter19,Miscellanea
AppendixC.EditorConfigurations
SectionC.1.vim
SectionC.2.vile
SectionC.3.Emacs
SectionC.4.BBEdit
SectionC.5.TextWrangler
AppendixD.RecommendedModulesandUtilities
SectionD.1.RecommendedCoreModules

SectionD.2.RecommendedCPANModules
SectionD.3.UtilitySubroutines
AppendixBibliography.Bibliography
Colophon
AbouttheAuthor
Colophon
Index


PerlBestPractices
byDamianConway
Copyright©2005O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editors:

AllisonRandal
TatianaApandi

ProductionEditor:

Genevieved'Entremont

CoverDesigner:


EllieVolckhausen

InteriorDesigner:

DavidFutato

PrintingHistory:



July2005:

FirstEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
PerlBestPractices,theimageofanAmercianstaghound,and


relatedtradedressaretrademarksofO'ReillyMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.

ISBN:0-596-00173-8
[M]


Dedication
ForLinda


Preface
ThisbookisdesignedtohelpyouwritebetterPerlcode:infact,
thebestPerlcodeyoupossiblycan.It'sacollectionof256
guidelinescoveringvariousaspectsoftheartofcoding,
includinglayout,nameselection,choiceofdataandcontrol
structures,programdecomposition,interfacedesignand
implementation,modularity,objectorientation,errorhandling,
testing,anddebugging.Theseguidelineshavebeendeveloped
andrefinedoveraprogrammingcareerspanning22years.
They'redesignedtoworkwelltogether,andtoproducecode
thatisclear,robust,efficient,maintainable,andconcise.
Mindyou,that'snoteasytoachieve.Concisenesscanbethe
naturalenemyofclarity;efficiencythenemesisof
maintainability.Andarmouringcodetomakeitsufficiently
robustcanundermineclarity,efficiency,conciseness,and
maintainability.Sometimesit'sacaseof:"Chooseanyone."
Thisbookdoesn'ttrytooffertheonetrueuniversaland
unequivocalsetofbestpractices.Thereareasmanywaysof
measuringcodequality,andasmanydimensionsinwhichcode
canbejudged,asthereareprogrammerstomakethose
assessments.Eachprogrammerandeachprogrammingteam
willhavetheirownopinionsaboutthemostimportantand

desirableattributesofcode.
Whatthisbookoffersinsteadisasetofbestpractices:aset
thatiscoherent,widelyapplicable,balancedinitsaims,and
thatisbasedonreal-worldexperienceofhowcodeisactually
written,ratherthanonsomeone'sivory-towertheoriesonhow
codeoughtbecreated.Mostofall,it'sasetofpracticesthat
actuallywork,andthatmanydevelopersaroundtheworldare
alreadyusing.MuchlikePerlitself,theseguidelinesareabout
helpingyoutogetyourjobdone,withoutgettingintheway.


Ifyou'reanexperienceddeveloper,it'salmostcertainthatyou
won'tlikeallofthesuggestionsthatfollow.Youwillfindsome
ofthemunnaturalorcounterintuitive;othersmayfeel
excessivelyrigidandun-Perlish.Maybethey'lljustseem
unnecessarilydifferentfromthewaysyou'reusedtowriting
software,andfromthelong-ingrainedcodinghabitsyoufindso
comfortable.
Trytoputthosefeelingsasideasyoureadthroughtheadvicein
thisbook.Reviewitasyouwouldanyotherproposedcode
enhancement:analyzetheargumentsthataremadeforthese
newpractices;askyourselfwhetheryou'veeverfallenintothe
trapstheyseektoavoid;considerwhetherthecoding
techniquessuggestedheremightbeworthtrying.
Justthinkingabouttheseissuesbecomingconsciousoftheway
youcurrentlywritecodecanbeofenormousbenefit,evenifyou
don'tadoptasingleoneoftherecommendationsthatfollow.


ContentsofThisBook

Chapter1,BestPractices,explainswhyitmightbeworth
reassessingyourcurrentcodingpractices.Itdiscusseshow
codingstylesareevolved,andsetsoutthreebroadcriteria
againstwhichanyexistingorproposedcodingpracticecanbe
assessed.Thechapteralsoexplainswhygoodcodinghabits
matterandsuggestshowtheycanbedeveloped.
Chapter2,CodeLayout,tacklesthemanycontentiousissuesof
codelayout.Itsuggestshowtosetoutblockdelimiters;howto
visuallydistinguishbuilt-insandkeywordsfromsubroutinesand
variables;wheretoplaceoperators,terminators,delimiters,
andotherpunctuation;howtoimprovereadabilitybythe
consistentuseofwhitespace;theoptimalwidthforcodelines
andblockindents;howtosetoutlistsofvalues;andwhereto
breaklongexpressions.Itconcludesbyrecommendinga
convenienttoolthatautomatesmostoftheselayouttasks.
Chapter3,NamingConventions,presentsaseriesofguidelines
thatcanhelpyouchoosemoredescriptivenamesforvariables,
subroutines,andnamespaces.Italsodemonstrateshowthe
variouscomponentsofaconsistentnamingschemecanwork
togethertoimprovetheoverallmaintainabilityofcode,bothby
makingitmorereadableandbyreducingtheneedfor
deobfuscatorycomments.
Chapter4,ValuesandExpressions,providesasimplesetof
rulesthatcanhelpyouavoidcommonpitfallswhencreating
characterstrings,numbers,andlists.Topicsincludehowto
avoidunintendedvariableinterpolation(andnon-interpolation),
reliableandreadableapproachestononprintablecharacters,
definingconstants,avoidingbarewords,andtamingheredocs,
commas,longnumbers,andlists.
Chapter5,Variables,exploresarobustapproachtousing



variables.Itexplainstheinherentdrawbacksofpackageor
punctuationvariables,suggestingsaferalternativeswhere
possible,andsaferpracticeswheretherearenoalternatives.
Thesecondhalfofthechapterpresentsseveralefficientand
maintainabletechniquesofhandlingdatainarraysandhashes
usingthe"containerslicing"mechanism.
Chapter6,ControlStructures,examinesPerl'srichvarietyof
controlstructures,encouragingtheuseofthosethatareeasier
tomaintain,lesserror-prone,ormoreefficient.Thechapter
providesasetofsimpleguidelinesfordecidingwhichoffor,
while,ormapismostappropriateforagiventask.Theeffective
useofiteratorvariablesisalsodiscussed,includingthecommon
caseofneedingtoiteratehashentriesbykeyandvalue
simultaneously.
Chapter7,Documentation,suggestsaseriesoftechniquesthat
canmakedocumentingyourcodelesstedious,andtherefore
morelikely.Itadvocatesatemplate-basedapproachtoboth
userandtechnicaldocumentation,anddiscusseswhen,where,
andhowtowriteusefulandaccuratecomments.
Chapter8,Built-inFunctions,discussesbetterwaysofusing
someofPerl'smostpopularbuilt-infunctions,includingsort,
reverse,scalar,eval,unpack,split,substr,values,select,sleep,map,
andgrep.Italsosummarizesthemanyotheruseful"non-builtin"builtinsprovidedbytwomodulesfromthestandardPerl
distributionandonefromCPAN.
Chapter9,Subroutines,describesefficientandmaintainable
waystowritesubroutinesinPerl,includingtheuseof
positional,named,andoptionalarguments,argumentvalidation
anddefaults,safecallingandreturnconventions,predictable

returnvaluesinvariouscontexts,andwhysubroutine
prototypesandimplicitreturnsshouldbeavoided.
Chapter10,I/O,explainshowtoopenandclosefilesreliably,
whentouseline-basedinput,howtocorrectlydetect


interactiveapplications,theimportanceofprompting,andhow
besttoprovidefeedbacktousersduringlongnon-interactive
tasks.
Chapter11,References,offersadviceondemystifyingPerl's
manydereferencingsyntaxes,discusseswhysymbolic
referencescreatemoreproblemsthantheysolve,and
recommendswaystopreventcyclicreferencechainsfrom
causingmemoryleaks.
Chapter12,RegularExpressions,presentsguidelinesforusing
regularexpressions.Itrecommendstheuseofextended
formatting,suggestsasimplebutunusualfixforPerl's
confusing"single-line"and"multiline"matchingmodes,warns
oftheperilsofmatchingwhitespacetooprecisely,showshowto
avoidusingtheerror-pronenumericvariables,presentsa
robustapproachtobuildingcomplexregexesthatarestill
maintainable,givesseveralhintsonoptimizingslowmatches,
andconcludesbyexplainingwhennottouseregular
expressions.
Chapter13,ErrorHandling,advocatesacoherentexceptionbasedapproachtoerrorhandling,andexplainswhyexceptions
arepreferabletospecialreturnvaluesorflags.Italso
recommendstheuseofexceptionobjects,andexploresindetail
howtheycanbedeclared,created,thrown,caught,and
handled.
Chapter14,Command-LineProcessing,addressesthedesign

andimplementationofcommand-lineinterfaces,bothfor
individualprogramsandforapplicationsuites.Itrecommends
severalmodulesthatcanmakeyourcommand-lineinterfaces
moreconsistentandpredictable,andatthesametimecan
considerablyreducetheeffortrequiredtoimplementthose
interfaces.
Chapter15,Objects,andChapter16,ClassHierarchies,offera
robustandefficientapproachtocreatingobjectsandclass


hierarchiesinPerl.Thisapproachprovidesfullyencapsulated
objectswithnoperformancepenalty,andsupportssingleand
multipleinheritancewithouttheusualproblemsofattribute
collision,incompleteinitialization,partialdestruction,or
incorrectmethodautoloading.Chapter16alsointroducesanew
modulethatallowstheserobustandefficientclassestobebuilt
semi-automatically.
Chapter17,Modules,looksatnon-object-orientedmodules,
exploringthebestwaystocreatethem,designtheirinterfaces,
declareandchecktheirversionnumbers,andrefactorexisting
codeintothem.Thischapteralsodiscussesthemanyexisting
modulesthatarefreelyavailableaspartofthePerlstandard
libraryandonCPAN.
Chapter18,TestingandDebugging,encouragestheuseof
testing,advocatingtest-drivendesignanddevelopmentusing
thecoreTest::modules.Italsoofferstipsoneffective
debuggingtechniques,includingadescriptionofvarious
modulesandotherfreetoolsthatcanmakedebuggingeasier.
Chapter19,Miscellanea,offersseveraladditionalguidelineson
miscellaneoustopicssuchasrevisioncontrol,interfacingto

codewritteninotherlanguages,processingconfigurationfiles,
textformatting,tiedvariables,benchmarkingandprofilingyour
code,cachingtechniques,andsomegeneraladviceon
refactoring.
AppendixA,EssentialPerlBestPractices,summarizesthe30
mostimportantguidelinesinthebookinthreeone-pagelists.
AppendixB,PerlBestPractices,listsall256guidelines,with
cross-referencestotheirchaptersandlocations.AppendixC,
EditorConfigurations,providessomeusefulconfiguration
optionsfortheVim,Vile,Emacs,TextWrangler,andBBEdittext
editors.AppendixD,RecommendedModulesandUtilities,lists
andcross-referencesthevariousmodulesrecommended
throughoutthebook,andprovidesabriefsummaryoftheir
mostusefulsubroutines.AppendixEoffersashortbibliography.


ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthetextof
thisbook:

Italic
Indicatesemphasis,newterms,URLs,emailaddresses,
filenames,paths,andUnixutilities.

Constant-widthregular
Indicatescommands,variables,attributes,functions,
classes,namespaces,methods,modules,values,the
contentsoffiles,theoutputfromcommands,andcode
examplesthatbreakrecommendedpractices.


Constant-widthbold
Indicatescommandsandothertextthatshouldbetyped
literallybytheuser,andcodeexamplesthatdemonstrate
recommendedpractices.

Constant-widthitalic

Indicatestextthatshouldbereplacedwithuser-supplied
valuesandcommentswithincodeexamples.


CodeExamples
Thisbookisintendedtohelpyougetyourjobdone.Ingeneral,
youmayusethecodeinthisbookinyourprogramsand
documentation.YoudonotneedtocontactO'Reillyfor
permissionunlessyou'rereproducingasignificantportionofthe
code.Forexample,writingaprogramthatusesseveralchunks
ofcodefromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
O'Reillyappreciates,butdoesnotrequire,attribution.An
attributionusuallyincludesthetitle,author,publisher,and
ISBN.Forexample:"PerlBestPractices,byDamianConway.
Copyright2005O'ReillyMedia,Inc.,ISBN:0-596-00173-8".
Ifyoufeelthatyouruseofcodeexamplesmayfalloutsidefair
useorthegivenpermissionguidelines,feelfreetosenda

specificrequestto


Feedback
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Thereisawebpageforthisbookthatlistserrata,examples,
andanyadditionalinformation.Youcanaccessthispageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,see:



Acknowledgments
Everybookistheworkofamultitude.Inwritingthisone,I
havebenefittedfromthehelp,advice,andsupportofmanyof
themosttalentedpeopleinthePerlcommunity.Iwouldliketo
expressmydeepestgratitude:
ToLindaMui,myfirsteditor,forherseeminglylimitless
patienceandcontinuingfaith,whichgavemethefreedomto
eventuallyfindmytruesubject.

ToNatTorkington,mysecondeditor,forrefiringmyenthusiasm
forwriting,andforhisextraordinaryencouragement,support,
andmateshipoverthepastdecade.
ToAllisonRandalandTatianaApandi,mythirdeditors,fortheir
grace,composure,understanding,goodadvice,quietefficiency,
andverypracticalassistance.
ToSeanM.Burke,forhiscarefultechnicalanalysis,invaluable
grammaticaladvice,salientquestions,andforanespecially
brilliantfootnotethatIsorelywishIcouldhaveused.
ToNancyKotary,forgentlyimprovingmywritingwithher
superbcopy-editing.
ToLarryWall,forhisfriendshipandwisdomoverthepastfive
years,andforteachingmesomuchinthattime,nottheleast
ofall:humility.
ToAbigail,forbringingano-nonsenseapproachtoPerlcoding
andforinvaluableadviceonmanytopicsinparticular,regular
expressionsandinside-outobjects.
ToNateBailey,forhisunfailingsupportoverthepastfewyears,
forhelpingmecraftsentencesthatmakesensethefirsttime,
andforhisexpertsecond-handknowledgeofsociopathy.


ToHildoBiersma,forhisprofessionalperspectiveonthe
realitiesofdevelopinginlargeteamenvironments,andfor
considerablymoregoodsuggestionsthanIwasabletouseina
singlebook.
ToChrisDevers,forconsistentlybetterwordingsthroughoutthe
book,andforsavingmefromwritinganentireextrachapter,
whenaparagraphturnedouttobeenough.
ToRichardDice,formarshallingcompellingeconomic

argumentstokeepthereviewprocessontrack,andforfinding
metheperfectbusiness-likeoperands.
ToStephenEdmonds,forunearthingthreeverysubtlecoding
errorsthatwouldotherwisehavepassedmostannoyinglyinto
print.
ToPaulFenwick,forthemuch-neededteacher'sperspectivehe
broughttothepresentationoftheseideas,andforduly
withholdingbiscuitswhenIbrokemyownguidelines.
ToGarrettGoebel,forhisextraordinaryattentiontodetailand
hisremarkableabilitytoextrapolatefromthoseparticularsto
excellentgeneraladvice.
ToMickGoulish,forenthusiasticencouragement,sound
skepticaladvicewhenIwasunderpressure,andsomeofthe
bestlaughsI'veeverhad,rightwhenImostneededthem.
ToUriGuttman,forseeingthingsno-oneelsedid,inwaysthat
no-oneelsecould.
ToTreyHarris,forsoablyrepresentingtheexpertprogrammer
andtherebyinspiringmetofindbetterways,insteadofjust
easyways.
ToBrandHilton,forunsurpassedtypocorrection,hisuncanny
abilitytospotbugsincodesamples,andhisvaliantdefenceof
"unless".


×