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

OReilly perl hacks tips and tools for programming debugging and surviving may 2006 ISBN 0596526741

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 (1.9 MB, 550 trang )

PerlHacks
Bychromatic,DamianConway,Curtis"Ovid"Poe
...............................................
Publisher:O'Reilly
PubDate:May2006
PrintISBN-10:0-596-52674-1
PrintISBN-13:978-0-59-652674-0
Pages:296

TableofContents|Index

Withmorethanamilliondedicatedprogrammers,Perlhasproventobe
thebestcomputinglanguageforthelatesttrendsincomputingand
business.Whileotherlanguageshavestagnated,Perlremainsfresh
thankstoitscommunity-baseddevelopmentmodel,whichencouragesthe
sharingofinformationamongusers.Thistraditionofknowledge-sharing
allowsdeveloperstofindanswerstoalmostanyPerlquestiontheycan
dreamup.

AndyoucanfindmanyofthoseanswersrighthereinPerlHacks.Likeallbooksin
O'Reilly's"Hacks"series,PerlHacksappealstoavarietyofprogrammers,whetheryou'rea
experienceddeveloperoradabblerwhosimplyenjoysexploringtechnology.Eachhackis
ashortlesson-somearepracticalexercisesthatteachyouessentialskills,whileothers
merelyillustratesomeofthefunthingsthatPerlcando.Mosthackshavetwoparts:a
directanswertotheimmediateproblemyouneedtosolverightnowandadeeper,subtler
techniquethatyoucanadapttoothersituations.LearnhowtoaddCPANshortcutstothe
Firefoxwebbrowser,readfilesbackwards,writegraphicalgamesinPerl,andmuchmore.

Foryourconvenience,PerlHacksisdividedbytopic-notaccordingto
anysenseofrelativedifficulty-soyoucanskiparoundandstopatanyhackyoulike.
Chaptersinclude:



ProductivityHacks
UserInteraction


DataMunging
WorkingwithModules
ObjectHacks
Debugging

Whetheryou'reanewcomeroranexpert,you'llfindgreatvalueinPerl
Hacks,theonlyPerlguidethatofferssomething
usefulandfunforeveryone.


PerlHacks
Bychromatic,DamianConway,Curtis"Ovid"Poe
...............................................
Publisher:O'Reilly
PubDate:May2006
PrintISBN-10:0-596-52674-1
PrintISBN-13:978-0-59-652674-0
Pages:296

TableofContents|Index















































Copyright
creditsCredits
Preface
Chapter1.ProductivityHacks
Hack1.AddCPANShortcutstoFirefox
Hack2.PutPerldoctoWork
Hack3.BrowsePerlDocsOnline
Hack4.MaketheMostofShellAliases
Hack5.AutocompletePerlIdentifiersinVim
Hack6.UsetheBestEmacsModeforPerl
Hack7.EnforceLocalStyle
Hack8.Don'tSaveBadPerl
Hack9.AutomateCheckinCodeReviews
Hack10.RunTestsfromWithinVim
Hack11.RunPerlfromEmacs
Chapter2.UserInteraction
Hack12.Use$EDITORAsYourUI
Hack13.InteractCorrectlyontheCommandLine
Hack14.SimplifyYourTerminalInteractions
Hack15.AlertYourMac

Hack16.InteractiveGraphicalApps
Hack17.CollectConfigurationInformation
Hack18.RewritetheWeb
Chapter3.DataMunging

















































































Hack19.TreataFileAsanArray
Hack20.ReadFilesBackwards
Hack21.UseAnySpreadsheetAsaDataSource
Hack22.FactorOutDatabaseCode
Hack23.BuildaSQLLibrary
Hack24.QueryDatabasesDynamicallyWithoutSQL
Hack25.BindDatabaseColumns

Hack26.IterateandGenerateExpensiveData
Hack27.PullMultipleValuesfromanIterator
Chapter4.WorkingwithModules
Hack28.ShortenLongClassNames
Hack29.ManageModulePaths
Hack30.ReloadModifiedModules
Hack31.CreatePersonalModuleBundles
Hack32.ManageModuleInstallations
Hack33.PresolveModulePaths
Hack34.CreateaStandardModuleToolkit
Hack35.WriteDemosfromTutorials
Hack36.ReplaceBadCodefromtheOutside
Hack37.DrinktotheCPAN
Hack38.ImproveExceptionalConditions
Hack39.SearchCPANModulesLocally
Hack40.PackageStandalonePerlApplications
Hack41.CreateYourOwnLexicalWarnings
Hack42.FindandReportModuleBugs
Chapter5.ObjectHacks
Hack43.TurnYourObjectsInsideOut
Hack44.SerializeObjects(Mostly)forFree
Hack45.AddInformationwithAttributes
Hack46.MakeMethodsReallyPrivate
Hack47.AutodeclareMethodArguments
Hack48.ControlAccesstoRemoteObjects
Hack49.MakeYourObjectsTrulyPolymorphic
Hack50.AutogenerateYourAccessors
Chapter6.Debugging
Hack51.FindCompilationErrorsFast
Hack52.MakeInvisibleCharactersApparent

Hack53.DebugwithTestCases
Hack54.DebugwithComments

















































































Hack55.ShowSourceCodeonErrors
Hack56.DeparseAnonymousFunctions
Hack57.NameYourAnonymousSubroutines
Hack58.FindaSubroutine'sSource
Hack59.CustomizetheDebugger
Chapter7.DeveloperTricks
Hack60.RebuildYourDistributions
Hack61.TestwithSpecifications
Hack62.SegregateDeveloperandUserTests

Hack63.RunTestsAutomatically
Hack64.SeeTestFailureDiagnosticsinColor!
Hack65.TestLiveCode
Hack66.CheatonBenchmarks
Hack67.BuildYourOwnPerl
Hack68.RunTestSuitesPersistently
Hack69.SimulateHostileEnvironmentsinYourTests
Chapter8.KnowThyCode
Hack70.UnderstandWhatHappensWhen
Hack71.InspectYourDataStructures
Hack72.FindFunctionsSafely
Hack73.KnowWhat'sCoreandWhen
Hack74.TraceAllUsedModules
Hack75.FindAllSymbolsinaPackage
Hack76.PeekInsideClosures
Hack77.FindAllGlobalVariables
Hack78.IntrospectYourSubroutines
Hack79.FindImportedFunctions
Hack80.ProfileYourProgramSize
Hack81.ReusePerlProcesses
Hack82.TraceYourOps
Hack83.WriteYourOwnWarnings
Chapter9.ExpandYourPerlFoo
Hack84.DoubleYourDatawithDualvars
Hack85.ReplaceSoftReferenceswithRealOnes
Hack86.OptimizeAwaytheAnnoyingStuff
Hack87.LockDownYourHashes
Hack88.CleanUpattheEndofaScope
Hack89.InvokeFunctionsinOddWays
Hack90.GlobThoseSequences





























Hack91.WriteLessError-CheckingCode
Hack92.ReturnSmarterValues

Hack93.ReturnActiveValues
Hack94.AddYourOwnPerlSyntax
Hack95.ModifySemanticswithaSourceFilter
Hack96.UseSharedLibrariesWithoutXS
Hack97.RunTwoServicesonaSingleTCPPort
Hack98.ImproveYourDispatchTables
Hack99.TrackYourApproximations
Hack100.OverloadYourOperators
Hack101.LearnfromObfuscations
Colophon
Index


Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheHacksseriesdesignations,PerlHacks,theimageofapair
ofworkboots,andrelatedtradedressaretrademarksof
O'ReillyMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.

wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
Smallprint:Thetechnologiesdiscussedinthispublication,the
limitationsonthesetechnologiesthattechnologyandcontent
ownersseektoimpose,andthelawsactuallylimitingtheuseof
thesetechnologiesareconstantlychanging.Thus,someofthe
hacksdescribedinthispublicationmaynotwork,maycause
unintendedharmtosystemsonwhichtheyareused,ormay
notbeconsistentwithapplicableuseragreements.Youruseof


thesehacksisatyourownrisk,andO'ReillyMedia,Inc.
disclaimsresponsibilityforanydamageorexpenseresulting
fromtheiruse.Inanyevent,youshouldtakecarethatyouruse
ofthesehacksdoesnotviolateanyapplicablelaws,including
copyrightlaws.




Credits
AbouttheAuthors
chromaticworksforO'ReillyMedia,whereheeditsthefreeand
opensourcewebsitesoftheO'ReillyNetwork.Inhisspare
time,hewritesbookssuchasthisone.Intheremaining
minutes,hecontributestotheCPAN,Perl5,Perl6,Parrot,and

evenPugs.HelivesjustwestofPortland,Oregonbyaparkand
acreekandwouldliketofinishmoreprojectssomeday,
includingwritinganovel,acomicbook,atelevisionshow,and
sleeping.Catchuponhishobbiesat />Dr.DamianConwayisaprofessionalPerlboffin.Astheauthor
ofnumerouspopularCPANmodules
(andtwohighlyregarded
booksonPerl,heisalsoawidelysought-afterconference
speakerandrunsaninternationalITtraining
companyThoughtstream()which
providesPerltrainingfrombeginnertomasterclasslevel
throughoutEurope,NorthAmerica,andAustralasia.Hespends
mostofhisless-than-copiousfreetimeworkingwithLarryWall
onthedesignofPerl6.[Hack#5],[Hack#13],[Hack#14],
[Hack#34],[Hack#54],[Hack#86],[Hack#90],[Hack#92],
[Hack#93],[Hack#94],[Hack#95],[Hack#99],[Hack
#100]
Earlierthiscentury,displayinghisusualstellarsenseoftiming,
Curtis"Ovid"Poeswitchedfrommainframestoweb
programminginPerlandpromptlywatchedthedot-com
industryimplode.Despitethisminorsetbackandworkingfor
severalcurrentlynon-existentcompanies,OvidstuckwithPerl
andactuallydiscoveredhelikedit.Afrequentspeakeratuser
groupsandauthorofnumerousCPANmodulesandapopular
PerlCGIcourse,OvidisaPerlFoundationSteeringCommittee


memberandalsoheadstheTPFgrantcommittee.[Hack#10],
[Hack#31],[Hack#50],[Hack#56],[Hack#57],[Hack#58],
[Hack#60]


AbouttheContributors
Perlisalsoalanguagewitharichandvariedcommunityof
experts,wizards,gurus,goofs,andne'er-do-wells.Afewofthe
mostcolorfulcharacters[1]contributedtothisbook.
[1]Punstronglyintended.

AdrianHowardstillhopesthatLispandSmalltalkwilltakeover
theworld,butinthemeantimegetspaidforplayingwithPerl
andRubyamongstotherthings.Agilefanatic.Testingbigot.
Usabilityzealot.RecentlyguilttrippedintobeingaPerlGrant
ManagerbyOvid.Savingupforasmallcastletosharewithhis
belovedKathrynandasmallbandofloyalYorkshireTerriers.
[Hack#15],[Hack#63]
ChrisDolanisasoftwaredeveloperlivinginMadison,
Wisconsin.WithaPh.D.inAstronomy,hehasaverystrong
mathandsciencebackground.Hestartedprogramming
professionallyasateenagerinthelate1980s.Duringhisfree
time,heisanactiveparticipantinseveralonlinesoftware
developmentcommunitiesandisanavidbicyclist.[Hack#40]
DavidLandgrenstartedusingPerl4.019whenawkwasno
longersufficienttocopewiththethingshewastryingtodo.In
1999hefoundedtheParisPerlMongersandhelpedorganize
theYAPC::Europe2003conference.Hecurrentlyworksata
largeFrenchhumanresourcesfirm,wherehelikestogobythe
titleofITOperationsManager,usingPerleverywhere.He
spendswhatlittlesparetimehehasleftwritingsummariesfor
theperl5-portersmailinglist.Contacthimat
[Hack#98]



DavidWheeler,alongtimePerlhacker,madeanameforhimself
astheleaddeveloperoftheBricolagecontentmanagement
system,andasPresidentandfounderofKineticode
(),awebsoftwarecompany.His
workonBricolageledhimoverthelastyeartodevelopthe
KineticPlatform,anext-generationenterprisewebservices
applicationplatform.HelivesinPortland,Oregon.[Hack#7],
[Hack#28]
GuillaumeCottenceauisasoftwaredeveloper.He'sbeen
interestedincomputersfortoolongtoremember,enjoys
programmingwithvarioustoolsandlanguages,andfound
himselfluckyenoughtobethecatalystforagamewrittenin
Perlcalled"Frozen-Bubble"whichisregularlycitedasthe
favoritegameoftheLinuxcommunity.[Hack#16]
H.MerijnBrandisaPerl5porter,theConfigurepumpking,and
anAmsterdamPerlMonger.HewasbornonDecember30,
1961,ismarried,andhastwokids.Hehasworkedasadata
analystforPROCURAB.V.inTheNetherlandssinceJune1991.
Visithishomepageat />[Hack#21]
JesseVincentdoesn'tdrinkthatoften,butdoesfindthatadrink
ortwotendstoimprovetheCPANremarkably.[Hack#37]
JoeMcMahonisatestautomationarchitectatYahoo!whose
backgroundincludesextensivedevelopmentexperience:25
yearsofworkatNASA,witheverythingfromspacecraftground
communicationssystemstoWebdevelopment.Hehas
contributedtocorePerltestsupport,suppliedthedebuggers
internaldocumentation,andsupportsseveralCPANmodules,
fromApp::SimpleScanandWWW::Mechanize::Pluggableto
Date::PeriodParserandGraphViz::Data::Structure.[Hack#59]
JoshuabenJorecametoPerlbecausehehadtowriteaCGI

appforapoliticalcampaignandhe'dheardthatPerlwasbest
forthatsortofthing.Hestayedwhenhefoundoutforhimself


howwonderfulCPANwas.Hislatestprojectshavebeenworking
towardgettingLispymacrosandlazyevaluationinPerland
learningwhatProloghastooffer.Heiswell-knownat
perlmonks.orgunderthehandlediotaleviandadmitstobeinga
Morrisdancer.[Hack#83]
MichaelGrahamisaPerlprogrammerwholivesinToronto
wherehewriteswebapplicationswithCGI::Applicationandits
richsuiteofplug-ins.HeworksatWilder&Associates
().Helikesmusic,longwalksonthe
beach,andtest-drivendevelopment.[Hack#68],[Hack#69]
Philippe"BooK"Bruhat,authorofHTTP::ProxyandNet::Proxy,lives
inLyon,Francewithhiswifeandcatandisanactivememberof
theFrenchandEuropeanPerlcommunities.Heworkedonthe
translationsofProgrammingPerl,3rdEditionandPerlBest
PracticesforO'ReillyFrance,andpublishesPerlarticlesin
GNU/LinuxMagazineFrance.Astheco-developperofAct(A
ConferenceToolkit)andamemberoftheYAPCEurope
Foundation,hehelpsorganizeEuropeanPerlworkshopsand
conferences,atwhichheisalsoaregularspeaker.Hewould
loveitifyoutriedhisAcme::MetaSyntacticmodule(updated
weekly).[Hack#18],[Hack#97]
RicardoSignestrainedforacareerinphilosophy,butthe
suddenonsetoftheIndustrialRevolutionforcedhimtowork
withbaserformsoflogic.HelivesinBethlehem,Pennsylvania
andwritesPerlforPobox.com.[Hack#8]
SeanM.Burkeisaperfectlynormalhumanbeing,basedon

organicmolecules,andexhibitingbilateralsymmetry.Heis
typical.HehaswrittentwoO'Reillybooks,PerlandLWPand
RTFPocketGuide,hascontributeddozensofmodulestoCPAN,
andwasaregularcolumnistforThePerlJournalforaboutfive
years.(HisarticlesappearinthevariousO'ReillyBestofthe
PerlJournalbooks,notablytheGames,Diversions&Perl
Culturevolume.)Trainedasalinguist,henowlivesonanisland
insoutheastAlaska,wherehedevelopstoolsforNative


languagepreservation.Wildrumorsplacehiswebsiteat
.[Hack#3],[Hack#6],[Hack#11]
SimonWistowcurrentlyherdsLondon.pmthelargestandmost
rowdyofallthePerlMongergroups.Inhissparetimehewrites
rathertoomanyCPANmodulesofdubioususefulness.[Hack
#39]
StephenB.Jenkins(a.k.a.Erudil)isthesenior
programmer/analystattheAerodynamicsLaboratoryofthe
InstituteforAerospaceResearch,NationalResearchCouncilof
Canada.HehaswrittenforDr.Dobb'sJournal,LinuxJournal,
ThePerlJournal,theUSENIXAssociation,theAmerican
InstituteofAeronauticsandAstronautics,theAerospaceand
ElectronicsSystemsSocietyoftheIEEE,andtheAssociationfor
ComputingMachinery.Formoreinfo,see
.[Hack#101]
TimAllwineisaSeniorSoftwareEngineeratO'ReillyMedia,Inc.
HedevelopssoftwarefortheMarketResearchgroup,writes
variousspideringtoolsthatcollectdatafromdisparatesites,
andisinvolvedinthedevelopmentofwebservicesatO'Reilly.
[Hack#71]

TomMoertelisaregularcontributertothePittsburghPerl
Mongers.HecreatedTest::LectroTest,aspecification-based
testingsystemforPerl,andPXSL("pixel"),aconvenient
shorthandforwritingmarkup-heavyXMLdocuments.Healso
wroteTheCoder'sGuidetoCoffee,aconciseguidetothe
programmer'smostmisunderstoodutilitybeverage.Helivesin
Pittsburgh,Pennsylvania,whereherunsaconsultingpractice
specializinginsolvingdifficultsoftwareproblems.Readmore
abouthisprojectsandinterests,whichincludeespressoand
functionalprogramming,at.[Hack
#61]
BrettWarden,BSEE,specializesinPerlprogrammingand
embedded/telcosystems.HelivesintheNorthwestU.S.with


hiswifeandson.Youcanfindacollectionofoddprojectsat
HisPerlMonksusernameis
isotope.[Hack#42]

Acknowledgments
Theauthorswishtothanktheireditor,AllisonRandal,for
shepherdingtheprocessandsmoothingoutallofthenonwritingdetails,aswellastheproductionandmarketingand
businessdepartmentsatO'ReillyMediaforturningthisbook
fromplaintextintothelovelyprintedformyouholdinyour
hands.
ThanksalsotoNathanTorkingtonforhelpingtostartthis
process.

chromatic
Thanksgoprimarilytomyco-authors,twofineprogrammersit

ismyprivilegetoknowascolleaguesandfriends,aswellasto
allofthecontributors,withoutwhomthisbookwouldbemuch
shorter,muchlessinteresting,andmuchlessfun.Thanksalso
gotomyfriends,family,andcommiserators,especiallytheUof
PcrewandAleatha,Esther,Eva,Kate,Katie,Laura,andMel.
Thanksandrespectgotomyworkandhobbycolleagues,
includingalloftheprogrammerswhohaveinventedandrefined
thesetoolswhichallowustoworkandplay.
Finally,Idedicatethisbooktomyfamily,Brett,Danielle,Jacob,
Jack,andBradinthehopethatIamaworthybrother,brotherin-law,uncle,andcatcaretaker.

DamianConway


Tochromatic,Allison,andNat,forinvitingmetohelpthem
buildthiswonderfulnewPerljunglegym.ToLarryWall,who
inventedtheextraordinaryplaygrounduponwhichitis
constructed.Andtomymany,manyfriendsthroughoutthe
worldwidePerlcommunity,whoseencouragementandsupport
hasallowedmetoplayhereforthepastdecade.
Aboveall,tomybelovedLinda,whoselove,beauty,andgrace
illuminateeverydayofmylife.

Curtis"Ovid"Poe
There'snowayIcouldhaveparticipatedinthiswithoutthePerl
communityhavingpatientlyansweredsomanyofmysilly
questionswhenIstartedlearningPerlyearsago.Theydidn't
justteachmePerl,theytaughtmehowtobeaprogrammer.
ManythankstochromaticandAllisonforshrink-wrappingmy
monkey.I'llneverforgiveyou.Mostly,though,Iwanttothank

SeanandLil,twopeoplewithoutwhomtheworldwouldbea
sadderplaceforme.

TechnicalReviewers
Theauthorsextendtremendousthankstothetechnical
reviewerswhofoundmanyerrors,suggestedmanyrephrasings,
andarguedoverimportantformattingdetailstomakethisbook
clear,accurate,andinteresting.TheyareAnnBarcomb,Daniel
Bosold,BradBowman,Philippe"BooK"Bruhat,the#cgiappIRC
channel,ChrisDolan,MichaelGraham,GarickHamlin,Joshua
benJore,YvesOrton,RicardoSignes,andDavidWheeler.


Preface
Perlisalanguagewitharichandexpressivevocabulary.Since
itsoriginalreleasein1987,it'smovedfromquick-and-dirty
extractionandreportingtowebprogramming,datamunging,
GUIbuilding,automationgluing,andfull-blownapplication
development.It'stheducttapeoftheInternetandaSwissArmychainsaw.
Likeducttapeandmultitools,Perlcandojustaboutanything
youcanimagineandreallywanttodo.
Ifyoujustwanttogetyourjobdonequickly,youcanwritethe
simplest,easiestPerlyouknowandgoontootherthings.If
youwanttobuildbigapplications,youcandothatwithsome
experienceandalittlediscipline.Ifyouwanttosolveyour
problemanddon'tmindalittlehelp,theCPANistheretogive
youahand.
That'sallveryproductive,andbeingproductivecanbe
fulfilling...butPerlcanalsobefun.
Imaginealitterofkittens,tumblingacrossthefloorinaballof

teethandclawsandfurandtinylittlegrowls.They'replaying,
sure,butthey'realsopracticingtheskillstheyneedtosurvive
inthescarywildworld.They'recarefulnottohurteachother,
butthetacticsandsurprisesofonecleverkittencanteachthe
othersvaluablelessons.
WhatmakesaPerlguru?It'sknowledge,partly,butit'smostly
thecuriositytoplaywiththelanguage,discoversurprises,and
eveninventafewofyourown.That'swhythisbookwasso
muchfuntowrite.Hereare101tips,tricks,andtechniques
fromsomeofthebestPerlprogrammersintheworld.Someare
immediatelyproductive.Somearesneakattacksthatyoumight
onlyusewhenyouhavenootherchoice.Mostofthemhave


twoparts:theimmediateproblemyouneedtosolverightnow
andadeeper,subtlertechniquethatyoucanadapttoother
situations.Allofthemareworthstudying.
It'sgoodtobeproductive.That'swhyyouprograminPerl.Add
inthefunoflearningespeciallylessonsittookthesePerlgurus
yearstolearnandyou'llbereadyforanything.Amazeyour
friends.Astoundyourcoworkers.Walkintothejungleofcode
andspecificationsandcustomerrequestswiththeconfidence
thatyoucantakedownanyproblemthatjumpsoutatyou.
Youwill.

WhyPerlHacks?
Thetermhackinghasanunfortunatereputationinthepopular
press,whereitoftenreferstosomeonewhobreaksinto
systemsorwreakshavocwithcomputers.Amongenthusiasts,
ontheotherhand,thetermhackreferstoa"quick-n-dirty"

solutiontoaproblemoracleverwaytodosomething.The
termhackerisverymuchacompliment,praisingsomeonefor
beingcreativeandhavingthetechnicalchopstogetthings
done.O'Reilly'sHacksseriesisanattempttoreclaimtheword,
documentthewayspeoplearehacking(inagoodway),and
passthehackerethicofcreativeparticipationontoanew
generationofhackers.Seeinghowothersapproachsystems
andproblemsisoftenthequickestwaytolearnaboutanew
technology.
It'salsofun.
Ofcourse,nosinglebookcouldpossiblydocumentallofthe
interestingandcreativeandmind-expandingthingspeoplecan
anddoachievewithPerl...butwehopethisbookwillputyouin
therightmindsettohackyourowncrazyideas.


HowToUseThisBook
We'vedividedthisbookalongvarioustopics,notaccordingto
anysenseofrelativedifficulty.Skiparoundandflipthroughthe
book;ifyouseeaninterestingtitleorsomeparagraphcatches
youreye,readit!Wherepossible,we'veaddedcrossreferences
torelatedhacksinthetext.Forexample,ifyouandyour
coworkersarerightnowcelebratingbeer-thirtyonalazyFriday
afternoon,startwith"DrinktotheCPAN"[Hack#37].

HowThisBookIsOrganized

Chapter1,ProductivityHacks
Admitit.Whenyousitdowntocode,somethingannoys
you.Itmayberepetitivecommands,lookingup

documentation,orthefactthatyourcoworkersjustcan't
aligntheirequalssigns.Gettingridofthoseinterruptions
andannoyanceswillmakeyourlifeeasierandyourcoding
sessionsmoreenjoyable.Thischaptersuggestsafewideas.

Chapter2,UserInteraction
Menus,graphics,beeps,andcommandlines:theseareall
waysyourprogramsgrabuserattention.Doitkindly.Doit
withstyle.Doitwithconvenience.Thischapterisallabout
workingwithotherpeople.

Chapter3,DataMunging
WhatdoesPerllovetoextractandreport?Data!Hookitup


todatabasesandsetitlooseonfiles.It'ssoeasyyoumight
notrealizethatyourcodeis,well,slowandkludgy.That's
okay.Takethetipsinthischaptertoheartandyoucan
polishyourPerltosliceanddicedataagain.

Chapter4,WorkingwithModules
Perl5'sunitofreusablecodeisthemodule.Whenyou
unleashthepowerofmoduleswhetheryourownorthose
writtenbyotherpeopleyou'reontracktobecomingareal
guru.Todothat,youneedtogobeyondtheidea"onefile,
onenamespace,onemodule."Youneedtounderstandwhat
makesthemworkandhowtoexploitalloftheclever
possibilitiestheyprovide.Thischapterleadstheway.

Chapter5,ObjectHacks

Abstraction,encapsulation,andgenericityarethekeysto
designinglarge,maintainablesystems.Objectsareoneway
togo.Sure,somepeopleclaimthatPerldoesn'treallydo
OO,butthey'rewrongandyoucanproveit.Gobeyondthe
blessedhashesandfindwaystobuildpowerfulabstractions
inthischapter.

Chapter6,Debugging
Ofcourseyourcodeworks,butsomedayyou'llhavetodig
throughapileofPerlleftbyanobnoxiouscoworker(evenif
thatwasyoubeforeyoureadthisbook).Don'tgoin
unarmed.Prepareyourselffortheworstwithatoolkitfullof
tipsandtechniquestodisarmthehairiest,weirdestcode
youcanimagine.Thischapterwillshinelightonthose
lurkingmonsters(andthey'renotsobadonceyougetto


knowthem).

Chapter7,DeveloperTricks
Maintainingaprogramisdifferentfrommaintainingan
entiresystem.Thisisdoublytrueifyouworkwithother
people.Ifanything,disciplineandconsistencyaremore
importantthanever.Ofcourse,soarecleverwaysto
convinceotherpeopletodotherightthing.Needsome
leveragetogetyourshopinshape?Thischapterhas
answers.

Chapter8,KnowThyCode
"Knowthyself,"theinscriptionsaid.Thisistheoracleof

Perl,notDelphi,sotheadmonitionisalittledifferent.Ifyou
reallywanttotakeadvantageofthedeepermysteriesof
Perl,youhavetobeabletolookdeeplyintothelanguage,
thelibraries,andtheinterpreteritselfaswellasyourown
codeandunderstandwhat'shappening.Thischapterwill
takeyoufromprogrammertoguru.Hangon.

Chapter9,ExpandYourPerlFoo
Whenthephrase"PerlFu"justisn'tmetasyntacticenough,
it'stimetomoveonto"PerlFoo."Almostnoonehas
exploredeverycornerofPerl.There'sjusttoomuchto
learn.Untilnowtherehavebeennomaps.Thischapterwill
fillyourheadwithafewoftheodderideasintheworldof
Perl.Thenyou'llbereadytodiscoveryourown.

ConventionsUsedinThisBook


Thisbookusesthefollowingtypographicalconventions:

Plaintext
Indicatesmenutitles,menuoptions,andmenubuttons.

Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,anddirectories.

Constantwidth
Indicatescommands,options,switches,variables,
attributes,keys,functions,thecontentsoffiles,andthe

outputfromcommands.

Constantwidthbold
Showscommandsorothertextthatyoushouldtype
literally.

Constantwidthitalic

Showstextthatyoushouldreplacewithuser-supplied
values.

Graytype


Usedtoindicateacross-referencewithinthetext.

Thisiconsignifiesatip,suggestion,orgeneralnote.

Thisiconindicatesawarningorcaution.

Thethermometericons,foundnexttoeachhack,indicatethe
relativecomplexityofthehack:

UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor

distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution


usuallyincludesthetitle,author,publisher,andISBN.For
example:"PerlHacksbychromaticwithDamianConwayand
Curtis'Ovid'Poe.Copyright2006O'ReillyMedia,Inc.,0-59652674-1."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat


SafariEnabled
WhenyouseeaSafari®Enabledicononthecoverofyour
favoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.

We'dLiketoHearfromYou
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.

1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheU.S.orCanada)
707-829-0515(international/local)
707-829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcanaccessthis
pageat:


/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:
/>



Chapter1.ProductivityHacks
Hacks1-11
Everyonewantstobemoreproductive.That'sprobablywhyyou
usePerl:togetmoreworkdoneinlesstimewithlesswork.
Productivityisn'tallaboutsavingtime,though.Savingeffortis
evenmoreimportant,whetheryoumeanfindingthe
informationyouwant,automatingawayrepeatedtasks,or
findingwaysnottohavetothinkaboutthingsthatyoudoall
thetime.Insomeways,thisisthenotionofrelentless
automationfindingeverylittlenigglingtaskthatalways
interruptsyourcurrentprojectbybeingsoannoying,difficult,

cumbersome,ordifferentandthenhidingitbehindanalias,a
shellscript,aprocess,orwhatever.
Hereareafewideasforwaystomakeyourprogramminglife
easierandmoreproductive.Trythem,enjoyyournewsenseof
freetime,andletyourselfnoticethenewpointsoffrictionin
yourlife.Thensolvethem,too!


×