Вы находитесь на странице: 1из 183

ImpatientPerl

version:19January2010Copyright20042010

GregLondon
Permissionisgrantedtocopy,distributeand/ormodifythisdocument
underthetermsoftheGNUFreeDocumentationLicense,Version1.3
oranylaterversionpublishedbytheFreeSoftwareFoundation;
withnoInvariantSections,noFrontCoverTexts,andnoBackCoverTexts.
Acopyofthelicenseisincludedinthesectionentitled"GNU
FreeDocumentationLicense".

CoverArt(FrontandBack)onthepaperbackversionofImpatientPerlisexcludedfromthis
license.CoverArtisCopyrightGregLondon2004,AllRightsReserved.
Forlatestversionofthisworkgoto:
TableofContents
1TheImpatientIntroductiontoPerl7
1.1Thehistoryofperlin100wordsorless7
1.2BasicFormattingforthisDocument7
1.3DoYouHavePerlInstalled8
1.4YourFirstPerlScript,EVER9
1.5DefaultScriptHeader9
1.6FreeReferenceMaterial10
1.7CheapReferenceMaterial10
1.8AcronymsandTerms10
2Storage11
2.1Scalars11
2.1.1ScalarStrings12
2.1.1.1StringLiterals12

2.1.1.2SinglequotesversusDoublequotes13
2.1.1.3chomp13
2.1.1.4concatenation13
2.1.1.5repetition13
2.1.1.6length13
2.1.1.7substr13
2.1.1.8split14
2.1.1.9join14
2.1.1.10qw15
2.1.1.11MultiLineStrings,HEREDocuments15
2.1.2ScalarNumbers16
2.1.2.1NumericLiterals16
2.1.2.2NumericFunctions16
2.1.2.3abs16
2.1.2.4int16
2.1.2.5trigonometry(sin,cos,tan)17
2.1.2.6exponentiation17
2.1.2.7sqrt17
2.1.2.8naturallogarithms(exp,log)18
2.1.2.9randomnumbers(rand,srand)18
2.1.3ConvertingBetweenStringsandNumbers19
2.1.3.1Stringify19
2.1.3.1.1sprintf19

2.1.3.2Numify20
2.1.3.2.1oct21
2.1.3.2.2hex21
2.1.3.2.3BaseConversionOverview21
2.1.4UndefinedandUninitializedScalars22
2.1.5Booleans23
2.1.5.1FALSE24
2.1.5.2TRUE24
2.1.5.3Comparators25
2.1.5.4LogicalOperators26
2.1.5.4.1DefaultValues27
2.1.5.4.2FlowControl27
2.1.5.4.3Precedence27
2.1.5.4.4AssignmentPrecedence27
2.1.5.4.5FlowControlPrecedence28
2.1.5.4.6ConditionalOperator28
2.1.6References29
2.1.7Filehandles31
2.1.8ScalarReview32
2.2Arrays32
2.2.1scalar(@array)33
2.2.2push(@array,LIST)34
2.2.3pop(@array)34

2.2.4shift(@array)35
2.2.5unshift(@array,LIST)35
2.2.6foreach(@array)36
2.2.7sort(@array)37
2.2.8reverse(@array)38
2.2.9splice(@array)39
2.2.10UndefinedandUninitializedArrays39
2.3Hashes39
2.3.1exists($hash{$key})41
2.3.2delete($hash{key})42
2.3.3keys(%hash)42
2.3.4values(%hash)43
2.3.5each(%hash)43
2.4ListContext47
2.5References49
2.5.1NamedReferents50
2.5.2ReferencestoNamedReferents50
2.5.3Dereferencing50
2.5.4AnonymousReferents51
2.5.5ComplexDataStructures53
2.5.5.1Autovivification54
2.5.5.2MultidimensionalArrays55
2.5.5.3DeepCloning,DeepCopy56

2.5.5.4DataPersistence56
2.5.6StringificationofReferences56
2.5.7Theref()function57
3ControlFlow58
3.1Labels60
3.2lastLABEL60
3.3nextLABEL60
3.4redoLABEL60
4PackagesandNamespacesandLexicalScoping61
4.1PackageDeclaration61
4.2DeclaringPackageVariablesWithour62
4.3PackageVariablesinsideaLexicalScope62
4.4LexicalScope63
4.5LexicalVariables63
4.6GarbageCollection65
4.6.1ReferenceCountGarbageCollection65
4.6.2GarbageCollectionandSubroutines66
4.7PackageVariablesRevisited67
4.8Callinglocal()onPackageVariables68
5Subroutines69
5.1SubroutineSigil69
5.2NamedSubroutines69
5.3AnonymousSubroutines70

5.4Data::Dumperandsubroutines70
5.5PassingArgumentsto/fromaSubroutine70
5.6AccessingArgumentsinsideSubroutinesvia@_71
5.7DereferencingCodeReferences71
5.8ImpliedArguments72
5.9SubroutineReturnValue73
5.10ReturningFalse73
5.11Usingthecaller()FunctioninSubroutines74
5.12Thecaller()functionand$wantarray75
5.13ContextSensitiveSubroutineswithwantarray()75
6CompilingandInterpreting76
7CodeReuse,PerlModules78
8TheuseStatement78
9TheuseStatement,Formally79
9.1The@INCArray79
9.2TheuselibStatement80
9.3ThePERL5LIBandPERLLIBEnvironmentVariables80
9.4TherequireStatement80
9.5MODULENAME>import(LISTOFARGS)81
9.6TheuseExecutionTimeline82
10bless()83
11MethodCalls85
11.1Inheritance86

11.2usebase87
11.3INVOCANT>isa(BASEPACKAGE)88
11.4INVOCANT>can(METHODNAME)88
11.5InterestingInvocants88
12ProceduralPerl90
13ObjectOrientedPerl90
13.1Class92
13.2Polymorphism92
13.3SUPER93
13.4ObjectDestruction95
14ObjectOrientedReview96
14.1Modules96
14.2useModule96
14.3bless/constructors96
14.4Methods97
14.5Inheritance97
14.6OverridingMethodsandSUPER97
15CPAN98
15.1CPAN,TheWebSite98
15.2CPAN,ThePerlModule98
15.3PlainOldDocumentation(POD)andperldoc101
15.4CreatingModulesforCPANwithh2xs101
16TheNextLevel102

17CommandLineArguments102
17.1@ARGV103
17.2Getopt::Declare105
17.2.1Getopt::DeclareSophisticatedExample106
18FileInputandOutput108
18.1open108
18.2close108
18.3read108
18.4write109
18.5FileTests110
18.6FileGlobbing110
18.7FileTreeSearching111
19OperatingSystemCommands112
19.1Thesystem()function112
19.2TheBacktickOperator112
19.3OperatingSystemCommandsinaGUI112
20RegularExpressions113
20.1VariableInterpolation114
20.2WildcardExample115
20.3DefiningaPattern115
20.4Metacharacters116
20.5CapturingandClusteringParenthesis118
20.5.1$1,$2,$3,etcCapturingparentheses118

20.5.2Capturingparenthesesnotcapturing119
20.6CharacterClasses119
20.6.1MetacharactersWithinCharacterClasses120
20.7ShortcutCharacterClasses120
20.8Greedy(Maximal)Quantifiers121
20.9Thrifty(Minimal)Quantifiers121
20.10PositionAssertions/PositionAnchors122
20.10.1The\bAnchor122
20.10.2The\GAnchor123
20.11Modifiers125
20.11.1GlobalModifiers125
20.11.2ThemAndsModifiers125
20.11.3ThexModifier127
20.12ModifiersForm{}Operator128
20.13Modifiersfors{}{}Operator128
20.14Modifiersfortr{}{}Operator128
20.15Theqr{}function128
20.16CommonPatterns128
20.17Regexp::Common129
21ParsingwithParse::RecDescent130
22Perl,GUI,andTk133
23GNUFreeDocumentationLicense134

Aquickexplanationoftherevisionhistory.

IlosttheoriginalOpenOfficefilesforImpatientPerl.Torecover,Ihadtotakethe
PDF,copyandpastethetext,andthenmanuallyreformatthedocumentto
resembleitsoriginallayout.Itwaspainfullytedious,buttherevisionon17
February2009isthatreconstructedversion.Oneoftheproblemswiththatversion
isthatthetexthadhardreturnscodedintoitfromthecut/paste.Itmightlooklike
there'safourlineparagraphonsomepage,butit'sreallyfourlineswithhard
coded\nattheendofeachline.TheJanuary2010versionattemptstoremoveall
thehardcodedreturnsintheparagraphtextandallowthewordprocessorto
determinewheretowrapthetext.WhileIwasworkingonthatrev,Ifixedacouple
oftyposandtweakedasentenceortwo.Enjoy!GregLondon

1TheImpatientIntroductiontoPerl
Thisdocumentisforpeoplewhoeitherwanttolearnperlorarealreadyprogramminginperl
andjustdonothavethepatiencetoscroungeforinformationtolearnanduseperl.This
documentshouldalsofinduseasahandydeskreferenceforsomeofthemorecommonperl
relatedquestions.

1.1Thehistoryofperlin100wordsorless
Inthemid1980s,LarryWallwasworkingasasysadminandfoundthatheneededtodoanumberof
common,yetoddballfunctionsoverandoveragain.Andhedidnotlikeanyofthescriptinglanguages
thatwerearoundatthetime,soheinventedPerl.Version1wasreleasedcirca1987.Afewchanges
haveoccurredbetweenthenandnow.ThecurrentversionofPerlhasexceeded5.8.3andisahighly
recommendedupgrade.
Perl6isonthedrawingboardasafundamentalrewriteofthelanguage.Itisnotavailable
yet,andprobablywillnotbeavailableforsometime.

1.2BasicFormattingforthisDocument
Thisdocumentisformattedintotextsections,codesections,andshellsections.Thissentenceispartof
atextsection.Textsectionswillextendtothefarleftmarginandwilluseanonmonospacedfont.Text
sectionscontaindescriptivetext.

Codesectionsareindented.
Theyalsouseamonospacedfont.
Thisisacodesection,whichrepresents
codetotypeintoascript.
YouwillneedtouseaTEXTEDITOR,
notaWORDPROCESSORtocreatethesefiles.
Generally,thecodeiscontainedinonefile,
andisexecutedviaashellcommand.
Ifthecodesectioncoversmultiplefiles,
eachfilewillbelabeled.
###filename:MyFile.pm
Thiscodewillbeplacedina
filecalledMyFile.pm
#!/usr/local/envperl
###filename:myscript.pl
Thiscodewillbeplacedinafile
calledmyscript.pl
Thefirstlineofmyscript.plwillbethe
linewith#!/usr/local/envperl
>shellsectionsareindentedlikecodesections
>shellsectionsalsousemonospacedfonts.
>shellsectionsdifferfromcodesectionsin
>thatshellsectionsstartwitha'>'character

>whichrepresentsashellprompt.
>shellsectionsshowcommandstotypeon
>thecommandline.
>shellsectionsalsoshowtheoutputofascript,
>ifanyexists.
>Insimpleexamples,thecodeisshownina
>codesection,immediatelyfollowedbytheoutput
>fromrunningthescript.Thecommandtorun
>thescriptisdroppedtosavespace.

Asanexample,thecodeforasimple"HelloWorld"scriptisshownhere.Itcanbetypedinto
afileofanyname.Thenameofthefileisnotimportant.Thecommandtoexecutethescript
isnotimportanteither.Inthisexample,thecodeisimportant,andtheoutputisimportant,so
theyaretheyonlythingsshown.
print"HelloWorld\n"
>HelloWorld

THISDOCUMENTREFERSTO(LI/U)NIXPERLONLY.MuchofthiswilltranslatetoMac
PerlandWindowsPerl,buttheexacttranslationwillbeleftasanexercisetothereader.

1.3DoYouHavePerlInstalled
Tofindoutifyouhaveperlinstalledanditsversion:
>perlv

Youshouldhaveatleastversion5.8.3.Ifyouhaveanolderversionorifyouhavenoperl
installedatall,youcandownloaditforfreefromCPANisanacronymforComprehensivePerl
ArchiveNetwork.TheCPANsitecontainsthelatestperlfordownloadandinstallation,aswell
asaTONofperlmodulesforyouruse.Ifyouareabeginner,getyoursysadmintoinstallperl
foryou.Evenifyouarenotabeginner,getyoursysadmintoinstallperlforyou.

1.4YourFirstPerlScript,EVER

Createafilecalledhello.plusingyourfavoritetexteditor.Typeinthefollowing:
#!/usr/bin/envperl
usewarnings
usestrict#comment
print"HelloWorld\n"

(The#!onthefirstlineissometimespronounced"shebang")(The.plextensionissimplya
standardacceptedextensionforperlscripts.)Runthescript:
>perlhello.pl
HelloWorld

Thiscallsperlandpassesitthenameofthescripttoexecute.Youcansaveyourselfalittle
typingifyoumakethefileexecutable:
>chmod+xhello.pl

Andthenrunthescriptdirectly.
>hello.pl
HelloWorld

If"."isnotinyourPATHvariable,youwillhavetorunthescriptbytyping:
>./hello.pl

HOORAY!Nowgoupdateyourresume.Anythingfroma#charactertotheendofthelineisa
comment.

1.5DefaultScriptHeader
Allthecodeexamplesinthisdocumentareassumedtohavethefollowingscriptheader,
unlessotherwisestated.ItusesyourPATHenvironmentvariabletodeterminewhichperl
executabletorun.Ifyouneedtohavedifferentversionsofperlinstalledonyoursystem,you
cancontrolwhichversionofperltheywillrunbychangingyourPATHvariablewithouthaving
tochangeyourscript.
#!/usr/bin/envperl
usewarnings

usestrict

useData::Dumper
NotethatData::Dumpertakessometimetoloadandyouwouldn'twant
touseData::Dumperonsometimingcriticalproject.Butfor
learningperlwithsimplescripts,theexecutionspeedisn'tthat
highofapriority.Ifyou'rewritingarealscript(i.e.one
wheretimetorunandmemoryusageareissuestobeconsidered),
thendon'tuseData::Dumperbydefault,onlyuseitifyoureally
needit.

1.6FreeReferenceMaterial
Youcangetquickhelpfromthestandardperlinstallation.
>perlh
>perldoc
>perldoch
>perldocperldoc

FAQsonCPAN:http://www.cpan.org/cpanfaq.htmlMailingListsonCPAN:
http://list.cpan.orgMorefreedocumentationontheweb:http://www.perldoc.comStillmorefree
documentationontheweb:http://learn.perl.org

1.7CheapReferenceMaterial
"ProgrammingPerl"byLarryWall,TomChristiansen,andJonOrwant.Highlyrecommended
booktohavehandyatalltimes.Itissometimesreferredtoasthe"CamelBook"bywayof
thecameldrawingonitscover.Thepublisher,O'Reilly,hasprintedenoughcomputerbooks
tochokea,well,camel,andeachonehasadifferentanimalonitscover.Thereforeifyou
hearreferencetosomeanimalbook,itisprobablyanO'Reillybook.Well,unlessitsthe
"DragonBook",becausethatreferstoabookcalled"Compilers"byAho,Sethi,andUllman.

1.8AcronymsandTerms

Perl:Originally,"Pearl"shortenedto"Perl"togainstatusasa4letterword.Nowconsidered
anacronymforPracticalExtractionandReportLanguage,aswellasPettyEclecticRubbish
Lister.Thenamewasinventedfirst.Theacronymsfollowed.Notethatthisis"Perl"witha
capital"P".The"perl"withalowercase"p"referstotheexecutablefoundsomewherenear
/usr/local/bin/perlCPAN:ComprehensivePerlArchiveNetwork.Seehttp://www.cpan.orgfor
more.DWIM:DoWhatIMean.Onceuponatime,thestandardmantraforcomputer
inflexibilitywasthis:"Ireallyhatethisdarnmachine,Iwishthattheywouldsellit.Itnever
doeswhatIwant,butonlywhatItellit."DWIMinessisanattempttoembedperlwith
telepathicpowerssuchthatitcanunderstandwhatyouwantedtowriteinyourcodeeven
thoughyouforgottoactuallytypeit.Well,alright,DWIMisjustawayofsayingthelanguage
wasdesignedbysomereallylazyprogrammerssothatyoucouldbeevenlazierthanthey
were.(TheyhadtowriteperlinC,sotheycouldnotbeTOOlazy.)
AUTOVIVIFY:"auto"meaning"self"."vivify"meaning"alive".Tobringoneselftolife.Generally
appliestoperlvariablesthatcangrantthemselvesintobeingwithoutanexplicitdeclarationfromthe
programmer.Partofperl'sDWIMness."Autovivify"isaverb.Thenounformis"autovivification".
Sometimes,autovivificationisnotwhatyoumeantyourcodetodo,andforsomereason,when"do
whatImean"meetsautovivificationinperl,autovivificationwins.
Andnow,aHaiku:
DoWhatIMeanand
Autovivification
sometimesunwanted

TMTOWTDI:ThereisMoreThanOneWayToDoIt.Anacknowledgmentthatany
programmingproblemhasmorethanonesolution.Ratherthanhaveperldecidewhich
solutionisbest,itgivesyouallthetoolsandletsyouchoose.Thisallowsaprogrammerto
selectthetoolthatwilllethimgethisjobdone.Sometimes,itgivesaperlnewbiejustenough
ropetohanghimself.FooFighters:AphraseusedaroundthetimeofWWIIbyradar
operatorstodescribeasignalthatcouldnotbeexplained.LaterbecameknownasaUFO.
Thishasnothingtodowithperl,exceptthat"foo"isacommonvariablenameusedin
perl.Fubar:AnotherWWIIphraseusedtoindicatethatamissionhadgoneseriouslyawryor
thatapieceofequipmentwasinoperative.AnacronymforFouledUpBeyondAllRecognition
andsimilarinterpretations.Thishasnothingtodowithperleither,exceptthatfubarsomehow
gotmangledintofoobar,andperlisoftenawashinvariablesnamed"foo"and"bar",

especiallyiftheprogrammerwishestohidethefactthathedidnotunderstandhiscodewell
enoughtocomeupwithbetternames.Ifyouusea$foovariableinyourcode,youdeserveto
maintainit.

2Storage
Perlhasthreebasicstoragetypes:Scalars,Arrays,andHashes.Themostbasicstoragetype
isaScalar.ArraysandHashesuseScalarstobuildmorecomplexdatatypes.

2.1Scalars
Scalarsareprecededwithadollarsignsigil.A"$"isastylized"S".
sigil:Asymbol.InPerlasigilreferstothesymbolinfrontofavariable.

ScalarscanstoreStrings,Numbers(integersandfloats),References,andFilehandles.Perlissmart
enoughtoknowwhichtypeyouareputtingintoascalarandhandleit.
my$diameter=42#Themykeyworddeclaresalexical
my$pi=3.1415#variable.Ifyoudon'tknowwhat
my$initial='g'#thatmeans,don'tworryaboutit,
my$name='JohnDoe'#itwillbeexplainedlater.
my$ref_to_name=\$name#Specifically,insection4

Without"usestrict"andwithoutdeclaringavariablewitha"my",usingavariablecausesperlto
createoneandinitializeittoundef.Thisundefvaluewillstringifyto""ornumifyto0,dependinghow
theundefinedvariableisused.Thisiscalledautovivication.(StringificationandNumificationare
coveredlater.)
Autovivify:tobringoneselftolife.
Insomesituations,autovivicationishandy.However,incertainsituations,autovivificationcan
beanunholymonster.
my$circumference=$pie*$diameter
#oops,$piedoesn'texist.Autovivifiedtoundef,

#numifiedto0,therefore$circumferenceiszero.

Withoutusewarningsusestrictperlwillautovivifyanewvariablecalled"pie",
initializeittozero,andassumethatiswhatyoumeanttodo.Thereisnoreasonthat
warningsandstrictnessshouldnotbeturnedoninyourscripts.

2.1.1ScalarStrings
Scalarscanstorestrings.Youdonothavetodeclarethelengthofthestring,perljust
handlesitforyouautomatically.
2.1.1.1StringLiterals

Stringliteralsmustbeinsingleordoublequotesoryouwillgetanerror.
printhello
Error:Unquotedstring"hello"mayclashwith
reservedword

Youcanusesinglequotesordoublequotestosetoffastringliteral:
my$name='mud'
my$greeting="hello,$name\n"
print$greeting
>hello,mud

Youcanalsocreatealistofstringliteralsusingtheqw()function.
my($first,$last)=qw(JohnDoe)
print"firstis'$first'\n"
print"lastis'$last'\n"
>firstis'John'
>lastis'Doe'
2.1.1.2SinglequotesversusDoublequotes

Singlequotedstringsarea"whatyouseeiswhatyouget"kindofthing.
my$name='mud'

print'hello$name'
>hello$name

DoublequotesmeansthatyougetSOMEvariableinterpolationduringstringevaluation.
Complexvariables,suchasahashlookup,willnotbeinterpolatedproperlyindoublequotes.
my$name='mud'
print"hello$name\n"
>hellomud

Note:adoublequoted"\n"isanewlinecharacter.
2.1.1.3chomp

Youmaygetridofanewlinecharacterattheendofastringbychompingthestring.The
chompfunctionremovesonenewlinefromtheendofthestringeveniftherearemultiple
newlinesattheend.Iftherearenonewlines,chompleavesthestringalone.Thereturnvalue
ofchompiswhatwaschomped(seldomused).
My$string="helloworld\n"
chomp($string)
warn"stringis'$string'\n"
>stringis'helloworld'...
2.1.1.4concatenation

Stringconcatenationusestheperiodcharacter"."
my$fullname='mud'."bath"
2.1.1.5repetition

Repeatastringwiththe"x"operator.
my$line=''x80#$lineiseightyhypens
2.1.1.6length

Findouthowmanycharactersareinastringwithlength().
my$len=length($line)#$lenis80
2.1.1.7substr

substr(STRING_EXPRESSION,OFFSET,LENGTH)

Spin,fold,andmutilatestringsusingsubstr().Thesubstrfunctiongivesyoufastaccessto
getandmodifychunksofastring.YoucanquicklygetachunkofLENGTHcharacters
startingatOFFSETfromthebeginningorendofthestring(negativeoffsetsgofromtheend).
Thesubstrfunctionthenreturnsthechunk.
my$chunk=substr('theraininspain',9,2)
warn"chunkis'$chunk'"
>chunkis'in'...

Thesubstrfunctioncanalsobeassignedto,replacingthechunkaswell.Youneedastring
containedinavariablethatcanbemodified,ratherthanusingaconstantliteralinthe
exampleabove.
my$string='theraininspain'
substr($string,9,2)='beyond'
warn"stringis'$string'"
>stringis'therainbeyondspain'...
2.1.1.8split
split(/PATTERN/,STRING_EXPRESSION,LIMIT)

Usethesplitfunctiontobreakastringexpressionintocomponentswhenthecomponentsare
separatedbyacommonsubstringpattern.Forexample,tabseparateddatainasinglestring
canbesplitintoseparatestrings.
my$tab_sep_data="John\tDoe\tmale\t42"
my($first,$last,$gender,$age)
=split(/\t/,$tab_sep_data)

Youcanbreakastringintoindividualcharactersbycallingsplitwithanemptystringpattern
"".The/PATTERN/insplit()isaRegularExpression,whichiscomplicatedenoughtogetits
ownchapter.However,somecommonregularexpressionPATTERNSforsplitare:
\ttabseparateddata
\s+whitespaceseparateddata

\s*,\s*commaseparateddata
2.1.1.9join
join('SEPARATORSTRING',STRING1,STRING2,...)

Usejointostitchalistofstringsintoasinglestring.
my$string=join("and",
'apples','bananas','peaches')
warn"stringis'$string'"
>stringis'applesandbananasandpeaches'...
2.1.1.10qw

Theqw()functiontakesalistofbarewordsandquotesthemforyou.
my$string=
join("and",qw(applesbananaspeaches))
warn"stringis'$string'"
>stringis'applesandbananasandpeaches'...
2.1.1.11MultiLineStrings,HEREDocuments

Perlallowsyoutoplaceamultilinestringinyourcodebyusingwhatitcallsa"here
document.
My$string=<<ENDOFDOCUMENT

DoWhatIMeanandAutovivificationsometimesunwantedENDOFDOCUMENT
warn"stringis'$string'
>stringis'DoWhatIMeanand
>Autovivification
>sometimesunwanted'at...

The'<<'indicatesaHEREdocument,followedbythenameofthelabelindicatingtheendof
theheredocument.Enclosingthelabelindoublequotesmeansthatperlvariablesinthe
documentwillgetinterpolatedasstrings.Enclosingthelabelinsinglequotesmeansthatno

stringinterpolationoccurs.Perlthenreadsthelinesafterthe'<<'asstringliteralcontentuntil
itseestheendofstringlabelpositionedatthebeginningofaline.

2.1.2ScalarNumbers
Perlgenerallyusesfloatsinternallytostorenumbers.Ifyouspecifysomethingthatis
obviouslyaninteger,itwilluseaninteger.Eitherway,yousimplyuseitasascalar.
my$days_in_week=7#scalar=>integer
my$temperature=98.6#scalar=>float
2.1.2.1NumericLiterals

Perlallowsseveraldifferentformatsfornumericliterals,includinginteger,floatingpoint,and
scientificnotation,aswellasdecimal,octal,andhexadecimal.Binarynumbersbeginwith
"0b"hexadecimalnumbersbeginwith"0x"Octalnumberbeginwitha"0"Allothernumeric
literalsareassumedtobedecimal.
my$solar_temp_c=1.5e7#centigrade
my$solar_temp_f=27_000_000.0#Fahrenheit
my$base_address=01234567#octal
my$high_address=0xfa94#hexadecimal
my$low_address=0b100101#binary
2.1.2.2NumericFunctions
2.1.2.3abs

Useabstogettheabsolutevalueofanumber.
my$var1=abs(3.4)#var1is3.4
my$var2=abs(5.9)#var2is5.9
2.1.2.4int

Use"int"toconvertafloatingpointnumbertoaninteger.Notethatthistruncateseverything
afterthedecimalpoint,whichmeansyoudoNOTgetrounding.Truncatingmeansthat
positivenumbersalwaysgetsmallerandnegativenumbersalwaysgetbigger.
my$price=9.95

my$dollars=int($price)
#dollarsis9,not10!falseadvertising!
my$y_pos=5.9
my$y_int=int($y_pos)
#y_intis5(5is"bigger"than5.9)

Ifyouwanttoroundafloattothenearestinteger,youwillneedtowriteabitofcode.Onewayto
accomplishitistousesprintf:
my$price=9.95
my$dollars=sprintf("%.0f",$price)
#dollarsis10
2.1.2.5trigonometry(sin,cos,tan)

Thesin,cos,andtanfunctionsreturnthesine,cosine,andtangentofavaluegivenin
RADIANS.IfyouhaveavalueinDEGREES,multiplyitby(pi/180)first.
my$angle=45#45deg
my$radians=$angle*(3.14/180)#.785rad
my$sine_deg=sin($angle)#0.707
my$sine_rad=sin($radians)#0.707

Ifyouneedinversesine,cosine,ortangent,thenusetheMath::TrigmoduleonCPAN.
2.1.2.6exponentiation

Usethe"**"operatortoraiseanumbertosomepower.
my$seven_squared=7**2#49
my$five_cubed=5**3#125
my$three_to_the_fourth=3**4#81
Usefractionalpowerstotakearootofanumber:
my$square_root_of_49=49**(1/2)#7

my$cube_root_of_125=125**(1/3)#5
my$fourth_root_of_81=81**(1/4)#3

Standardperlcannothandleimaginarynumbers.UsetheMath::ComplexmoduleonCPAN.
2.1.2.7sqrt

Usesqrttotakethesquarerootofapositivenumber.
my$square_root_of_123=sqrt(123)#11.0905
2.1.2.8naturallogarithms(exp,log)

Theexpfunctionreturnsetothepowerofthevaluegiven.Togete,callexp(1)
my$value_of_e=exp(1)#2.7183
my$big_num=exp(42)#2.7183**42=1.7e18

Thelogfunctionreturnstheinverseexp()function,whichistosay,logreturnsthenumberto
whichyouwouldhavetoraiseetogetthevaluepassedin.
my$inv_exp=log($big_num)#inv_exp=42

Ifyouwantanotherbase,thenusethissubroutine:
sublog_x_base_b{returnlog($_[0])/log($_[1])}
#wantthelogbase10of12345
#i.e.towhatpowerdoweneedtoraisethe
#number10togetthevalueof12345?
my$answer=log_x_base_b(12345,10)#answer=4.1

Notethatinversenaturallogscanbedonewithexponentiation,youjustneedtoknowthe
valueofthemagicnumbere(~2.718281828).Theexpfunctionisstraightforward
exponentiation:
#big_num=2.7183**42=1.7e18
my$big_num=$value_of_e**42

Naturallogarithmssimplyusetheinverseofthevalue(i.e.1/value)withexponentiation.
#inv_exp=2.7183**(1/1.7e18)=42

my$inv_exp=$value_of_e**(1/$big_num)
2.1.2.9randomnumbers(rand,srand)

Therandfunctionisapseudorandomnumbergenerator(PRNG).Ifavalueispassedin,rand
returnsanumberthatsatisfies(0<=return<=input)Ifnovalueispassedin,randreturnsa
numberintherange(0<=return<1)ThesrandfunctionwillseedthePRNGwiththevalue
passedin.Ifnovalueispassedin,srandwillseedthePRNGwithsomethingfromthe
systemthatwillgiveitdecentrandomness.Youcanpassinafixedvaluetoguaranteethe
valuesreturnedbyrandwillalwaysfollowthesamesequence(andthereforeare
predictable).YoushouldonlyneedtoseedthePRNGonce.Ifyouhaveaversionofperl
greaterthanorequalto5.004,youshouldnotneedtocallitatall,becauseperlwillcallsrand
atstartup.
2.1.3ConvertingBetweenStringsandNumbers

Manylanguagesrequiretheprogrammertoexplicitlyconvertnumberstostringsbefore
printingthemoutandtoconvertstringstonumbersbeforeperformingarithmeticonthem.
Perlisnotoneoftheselanguages.PerlwillattempttoapplyDoWhatIMeantoyourcode
andjustDoTheRightThing.Therearetwobasicconversionsthatcanoccur:stringification
andnumification.
2.1.3.1Stringify

Stringify:Convertingsomethingotherthanastringtoastringform.Perlwillautomatically
convertanumber(integerorfloatingpoint)toastringformatbeforeprintingitout.
my$mass=7.3
my$volume=4
warn"massis'$mass'\n"
warn"volumeis'$volume'\n"
>massis'7.3'...
>volumeis'4'...

Eventhough$massisstoredinternallyasafloatingpointnumberand$volumeisstored
internallyasaninteger,thecodedidnothavetoexplicitlyconvertthesenumberstostring
formatbeforeprintingthemout.Perlwillattempttoconvertthenumbersintotheappropriate

stringrepresentation.Ifyoudonotwantthedefaultformat,usesprintf.Ifyouwanttoforce
stringification,simplyconcatenateanullstringontotheendofthevalue.
my$mass=7.3#7.3
my$string_mass=$mass.=''#'7.3'
2.1.3.1.1sprintf

Usesprintftocontrolexactlyhowperlwillconvertanumberintostringformat.
sprintf(FORMAT_STRING,LIST_OF_VALUES)

Forexample:
my$pi=3.1415
my$str=sprintf("%06.2f",$pi)
warn"stris'$str'"
>stris'003.14'...

Decodingtheaboveformatstring:
%=>format
0=>fillleadingspaceswithzero
6=>totallength,includingdecimalpoint
.2=>puttwoplacesafterthedecimalpoint
f=>floatingpointnotation

Toconvertanumbertoahexadecimal,octal,binary,ordecimalformatedstring,usethe
followingFORMAT_STRINGS:
hexadecimal"%lx"Theletter'l'(L)
octal"%lo"indicatestheinputis
binary"%lb"aninteger,possibly
decimalinteger"%ld"aLonginteger.
decimalfloat"%f"
scientific"%e"

2.1.3.2Numify

Numify:Convertingsomethingotherthananumbertoanumericform.Sometimesyouhave
stringinformationthatactuallyrepresentsanumber.Forexample,ausermightenterthe
string"19.95"whichmustbeconvertedtoafloatbeforeperlcanperformanyarithmeticon
it.Youcanforcenumificationofavaluebyaddingintegerzerotoit.
my$user_input='19.95'#'19.95'
my$price=$user_input+0#19.95

IfthestringisNOTinbasetenformat,thenuseoct()orhex()
2.1.3.2.1oct

Theoctfunctioncantakeastringthatfitstheoctal,hexadecimal,orbinaryformat
andconvertittoaninteger.binaryformattedstringsmuststartwith"0b"hexadecimalformatted
stringsmuststartwith"0x"Allothernumbersareassumedtobeoctalstrings.Note:even
thoughthestringmightnotstartwithazero(asrequiredbyoctalliterals),octwillassumethe
stringisoctal.Thismeanscallingoct()onadecimalnumbercouldbeabadthing.Tohandlea
stringthatcouldcontainoctal,hexadecimal,binary,ORdecimalstrings,youcouldassume
thatoctalstringsmuststartwith"0".Then,ifthestringstartswithzero,calloctonit,else
assumeit'sdecimal.Thisexampleusesregularexpressionsandtheconditionaloperator.
my$num=($str=~m{^0})?oct($str):$str+0
2.1.3.2.2hex

Thehex()functiontakesastringinhexformatandconvertsittointeger.Thehex()functionis
likeoct()exceptthathex()onlyhandleshexbasestrings,anditdoesnotrequirea"0x"
prefix.
2.1.3.2.3BaseConversionOverview

Givenadecimalnumber:
my$decimal=12

Convertfromdecimaltoanotherbaseusingsprintf:
my$hex=sprintf("%lx",$decimal)
my$oct=sprintf("%lo",$decimal)
my$bin=sprintf("%lb",$decimal)

Ifyouwanttopadthemostsignificantbitswithzeroesandyouknowthewidth,usethis:
#08assumeswidthis8characters
my$p_hex=sprintf("%08lx",$decimal)
my$p_oct=sprintf("%08lo",$decimal)
my$p_bin=sprintf("%08lb",$decimal)

Ifyouhaveastringandyouwanttoconvertittodecimal,usetheconditionaloperatorand
oct().
subconvert_to_decimal{
($_[0]=~m{^0})?Oct($_[0]):$_[0]+0
}
warnconvert_to_decimal('42')#dec
warnconvert_to_decimal('032')#oct
warnconvert_to_decimal('0xff')#hex
warnconvert_to_decimal('0b1001011')#bin

Ifyouwanttoknowhowmanybitsitwouldtaketostoreanumber,convertittobinaryusing
sprintf(don'tpadwithzeros)andthencalllength()onit.
warnlength(sprintf("%lb",255))#8

2.1.4UndefinedandUninitializedScalars
Alltheexamplesaboveinitializedthescalarstosomeknownvaluebeforeusingthem.You
candeclareavariablebutnotinitializeit,inwhichcase,thevariableisundefined.Ifyouuse
ascalarthatisundefined,perlwillstringifyornumifyitbasedonhowyouareusingthe
variable.Anundefinedscalarstringifiestoanemptystring:""Anundefinedscalarnumifiesto
zero:0Withoutwarningsorstrictturnedon,thisconversionissilent.Withwarnings/stricton,
theconversionstilltakesplace,butawarningisemitted.Sinceperlautomaticallyperforms
thisconversionnomatterwhat,thereisnostringornumericoperationthatwilltellyouifthe
scalarisundefinedornot.Usethedefined()functiontotestwhetherascalarisdefinedor
not.Ifthescalarisdefined,thefunctionreturnsaboolean"true"(1)IfthescalarisNOT
defined,thefunctionreturnsaboolean"false"("").Ifyouhaveascalarwithadefinedvaluein

it,andyouwanttoreturnittoitsuninitializedstate,assignundeftoit.Thiswillbeexactlyasif
youdeclaredthevariablewithnoinitialvalue.
my$var#undef
print"test1:"
if(defined($var)){print"defined\n"}
else{print"undefined\n"}
$var=42#defined
print"test2:"
if(defined($var)){print"defined\n"}
else{print"undefined\n"}
$var=undef#undefasifneverinitialized
print"test3:"
if(defined($var)){print"defined\n"}
else{print"undefined\n"}
>test1:undefined
>test2:defined
>test3:undefined

2.1.5Booleans
Perldoesnothaveaboolean"type"perse.Instead,perlinterpretsscalarstringsand
numbersas"true"or"false"basedonsomerules:
1)Strings""and"0"areFALSE,
anyotherstringorstringificationisTRUE
2)Number0isFALSE,anyothernumberisTRUE
3)allreferencesareTRUE
4)undefisFALSE

NotethattheseareSCALARS.AnyvariablethatisnotaSCALARisfirstevaluatedinscalar
context,andthentreatedasastringornumberbytheaboverules.Thescalarcontextofan
ARRAYisitssize.Anarraywithoneundefvaluehasascalar()valueof1andistherefore
evaluatedasTRUE.Asubroutinereturnsascalaroralistdependingonthecontextinwhich
itiscalled.ToexplicitlyreturnFALSEinasubroutine,usethis:
returnwantarray()?():0#FALSE

Thisissufficientlytroublesometotypeforsuchacommonthingthatanemptyreturn
statementwithinasubroutinewilldothesamething:
return#FALSE
2.1.5.1FALSE

ThefollowingscalarsareinterpretedasFALSE:
integer0#false
float0.0#false
string'0'#false
string''#false
undef#false
2.1.5.2TRUE

ALLothervaluesareinterpretedasTRUE,whichmeansthefollowingscalarsareconsidered
TRUE,eventhoughyoumightnothaveexpectedthemtobefalse.
string'0.0'#true
string'00'#true
string'false'#true
float3.1415#true
integer11#true
string'yowser'#true

Ifyouaredoingalotofworkwithnumbersonavariable,youmaywishtoforcenumificationonthat
variable($var+0)beforeitgetsbooleantested,justincaseyouendupwithastring"0.0"instead

ofafloat0.0andgetsomeseriouslyhardtofindbugs.
Notethatthestring'0.0'isTRUE,but('0.0'+0)willgetnumifiedto0,whichisFALSE.Ifyou
areprocessinganumberasastringandwanttoevaluateitasaBOOLEAN,makesureyou
explicitlyNUMIFYitbeforetestingitsBOOLEANNESS.BuiltinPerlfunctionsthatreturna
booleanwillreturnanintegerone(1)forTRUEandanemptystring("")forFALSE.
2.1.5.3Comparators

Comparisonoperatorsreturnbooleans,specificallyaninteger1fortrueandanullstring""
forfalse.The"Comparison"operator("<=>"and"cmp")returna1,0,or+1,indicatingthe
comparedvaluesarelessthan,equalto,orgreaterthan.Distinctcomparisonoperatorsexist
forcomparingstringsandforcomparingnumbers.FunctionStringNumeric
Function

String

Numeric

equalto

eq

==

notequalto

ne

!=

lessthan

lt

<

greaterthan

gt

>

lessthanorequalto

le

<=

greaterthanorequalto

ge

>=

comparison

cmp

<=>

(lt=1,eq=0,gt=+1)

equalto
Notethatifyouuseastringoperatortocomparetwonumbers,youwillgettheiralphabetical
stringcomparison.Perlwillstringifythenumbersandthenperformthecompare.Thiswill

occursilentlyperlwillemitnowarning.Andifyouwantedthenumberscompared
numericallybutusedstringcomparison,thenyouwillgetthewrongresultwhenyoucompare
thestrings("9"lt"100").String"9"isgreaterthan(gt)string"100".Number9isless
than(<=)number100.Ifyouuseanumericoperatortocomparetwostrings,perlwillattempt
tonumifythestringsandthencomparethemnumerically.Comparing"John"<="Jacob"will
causeperltoconvert"John"intoanumberandfailmiserably.However,ifwarnings/strictis
noton,itwillfailmiserablyandSILENTLY,assigningthenumificationof"John"tointeger
zero.Thenumericcomparisonoperator'<=>'issometimescalledthe"spaceshipoperator".
2.1.5.4LogicalOperators

PerlhastwosetsofoperatorstoperformlogicalAND,OR,NOTfunctions.Thedifference
betweenthetwoisthatonesethasahigherprecedencethantheotherset.Thehigher
precedencelogicaloperatorsarethe'&&','||',and'!'operators.
function

operator

usage

returnvalue

AND

&&

$one&&$two

if($oneisfalse)$oneelse$two

OR

||

$one||$two

if($oneistrue)$oneelse$two

NOT

!$one

if($oneisfalse)trueelsefalse

Thelowerprecedencelogicaloperatorsarethe'and','or','not',and'xor'operators.
function

operator

usage

returnvalue

AND

and

$oneand

if($oneisfalse)$oneelse$two

$two

OR

or

$oneor$two

if($oneistrue)$oneelse$two

NOT

not

not$one

if($oneisfalse)trueelsefalse

XOR

xor

$onexor

if(($onetrueand$twofalse)or

$two

($onefalseand$twotrue))then
returntrueelsefalse

Bothsetsofoperatorsareverycommoninperlcode,soitisusefultolearnhowprecedence
affectstheirbehavior.Butfirst,someexamplesofhowtousethem.
2.1.5.4.1DefaultValues

Thissubroutinehastwoinputparameters($leftand$right)withdefaultvalues(1.0and2.0).
Iftheusercallsthesubroutinewithmissingarguments,theundefinedparameterswillinstead
receivetheirdefaultvalues.
submysub{
my($left,$right)=@_
$left||=1.0
$right||=2.0
#dealwith$leftand$righthere.
}
The'||='operatorisafancyshorthand.This:
$left||=1.0
isexactlythesameasthis:
$left=$left||1.0
2.1.5.4.2FlowControl

Theopen()functionherewillattempttoopen$filenameforreadingandattach$filehandleto
it.Ifopen()failsinanyway,itreturnsFALSE,andFALSEOR'edwithdie()meansthatperl
willevaluatethedie()functiontofinishthelogicalevaluation.Itwon'tcompletebecause
executionwilldie,buttheendresultiscodethatisactuallyquitereadable.
open(my$filehandle,$filename)
ordie"cantopen"

2.1.5.4.3Precedence

Thereasonweused'||'inthefirstexampleand'or'inthesecondexampleisbecausethe
operatorshavedifferentprecedence,andweusedtheonewiththeprecedenceweneeded.
2.1.5.4.4AssignmentPrecedence

Whenworkingwithanassignment,use'||'and'&&',becausetheyhaveahigherprecedencethan(and
areevaluatedbefore)theassignment'='.The'or'and'and'operatorshaveaprecedencethatisLOWER
thananassignment,meaningtheassignmentwouldoccurfirst,followedbyanyremaining'and'and
'or'operators.
Right:
my$default=0||1
#defaultis1

Wrong:
my$default=0or1
#defaultis0

Thesecond(wrong)exampleisequivalenttothis:
(my$default=0)or1

whichwillALWAYSassign$defaulttothefirstvalueanddiscardthesecondvalue.
2.1.5.4.5FlowControlPrecedence

Whenusinglogicaloperatorstoperformflowcontrol,use'or'and'and'operators,because
theyhavelowerprecedencethanfunctionsandotherstatementsthatformtheboolean
inputstothe'or'or'and'operator.The'||'and'&&'havehigherprecedencethanfunctionsand
mayexecutebeforethefirstfunctioncall.Right:
close$fhordie"Error:couldnotclose"

Wrong:
close$fh||die"Error:couldnotclose"

Thesecond(wrong)exampleisequivalenttothis:
close($fh||die"Error")

whichwillALWAYSevaluate$fhastrue,NEVERdie,andclose$fh.Ifclose()fails,thereturn

valueisdiscarded,andtheprogramcontinuesonitsmerryway.Itisalwayspossibleto
overrideprecedencewithparentheses,butitisprobablybettertogetinthehabitofusingthe
rightoperatorfortherightjob.
2.1.5.4.6ConditionalOperator

Theconditionaloperatormimicstheconditionaltestingofanifelseblock.Theconditional
operatorusesthreeoperands,andisalsocalledatrinaryoperator.Asithappens,the
conditionaloperatorisperl'sONLYtrinaryoperator,sopeoplesometimescallitthetrinaryor
ternaryoperatorwhentheymeanconditionaloperator.Aslongasperldoesn'taddanother
trinaryoperator,itsnotaproblem.Itisevenmorerarelycalledthe?:operator.Theconditional
operatorhasthisform:
my$RESULT=$BOOLEAN1?$VALUE1:$VALUE2

Thiscanberewrittenasanifelseblocklikethis:
my$RESULT
if($BOOLEAN1){
$RESULT=$VALUE1
}else{
$RESULT=$VALUE2
}

Theconditionaloperatorallowsyoutodeclarethevariableandperformtheassignmentallin
oneshortlineofcode.Notethat$BOOLEAN1,$VALUE1and$VALUE2canbereplacedby
anynormalperlexpression,ratherthanbeinglimitedtoasimplescalarvalue.One
interestingexpressionthatyoucouldreplace$VALUE2withisanotherconditionaloperator,
effectivelyallowingyoutocreateachainofifelsifelsifelsestatements.Forexample:
my$RESULT=
$BOOLEAN1?$VALUE1
:$BOOLEAN2?$VALUE2
:$BOOLEAN3?$VALUE3
:$BOOLEAN4?$VALUE4

:$VALUE5

Theaboveexampleisequivalenttothismouthful:
my$RESULT
if($BOOLEAN1){$RESULT=$VALUE1}
elsif($BOOLEAN2){$RESULT=$VALUE2}
elsif($BOOLEAN3){$RESULT=$VALUE3}
elsif($BOOLEAN4){$RESULT=$VALUE4}
eles{$RESULT=$VALUE5}

2.1.6References
Areferencepointstothevariabletowhichitrefers.ItiskindoflikeapointerinC,whichsays
"thedataIwantisatthisaddress".UnlikeC,youcannotmanuallyaltertheaddressofaperl
reference.Youcanonlycreateareferencetoavariablethatisvisiblefromyourcurrent
scope.Createareferencebyplacinga"\"infrontofthevariable:
my$name='John'
my$age=42
my$name_ref=\$name
my$age_ref=\$age

Perlwillstringifyareferencesothatyoucanprintitandseewhatitis.
warn"age_refis'$age_ref'"
>age_refis'SCALAR(0x812e6ec)'...

Thistellsyouthat$age_refisareferencetoaSCALAR(whichweknowiscalled$age).It
alsotellsyoutheaddressofthevariabletowhichwearereferringis0x812e6ec.Youcannot
referencifyastring.I.E.youcannotgiveperlastring,suchas"SCALAR(0x83938949)"and
haveperlgiveyouareferencetowhateverisatthataddress.Perlisprettyloosygoosey
aboutwhatitwillletyoudo,butnotevenperlissocrazyastogivepeoplecompleteaccess
tothesystemmemory.Youcandereferenceareferencebyputtinganextrasigil(ofthe
appropriatetype)infrontofthereferencevariable.

my$name='John'
my$ref_to_name=\$name
my$deref_name=$$ref_to_name
warn$deref_name
>John...

Referencesareinterestingenoughthattheygettheirownsection.ButIintroducethemhere
sothatIcanintroduceareallycoolmodulethatusesreferences:Data::Dumper.
Data::DumperwilltakeareferencetoANYTHINGandprintoutthethingtowhichitrefersina
humanreadableform.Thisdoesnotseemveryimpressivewithareferencetoascalar:
my$name='John'
my$ref_to_name=\$name
warnDumper\$ref_to_name
>$VAR1=\'John'

ButthiswillbeabsolutelyessentialwhenworkingwithArraysandHashes.

2.1.7Filehandles
Scalarscanstoreafilehandle.FileIOgetsitsownsection,butIintroduceitheretogivea
completepictureofwhatscalarscanhold.Givenascalarthatisundefined(uninitialized),
callingopen()onthatscalarandastringfilenamewilltellperltoopenthefilespecifiedbythe
string,andstorethehandletothatfileinthescalar.
open(my$fh,'>out.txt')
print$fh"helloworld\n"
print$fh"thisissimplefilewriting\n"
close($fh)

Thescalar$fhintheexampleaboveholdsthefilehandleto"out.txt".Printingtothe
filehandleactuallyoutputsthestringtothefile.ThereissomemagicgoingontherethatI
havenotexplained,butthatisaquickintrotoscalarfilehandles.

2.1.8ScalarReview
ScalarscanstoreSTRINGS,NUMBERS(floatsandints),REFERENCES,and
FILEHANDLES.Stringify:toconvertsomethingtoastringformatNumify:toconvertsomething
toanumericformatThefollowingscalarsareinterpretedasbooleanFALSE:
integer0,float0.0,string"0",string"",undef

AllotherscalarvaluesareinterpretedasbooleanTRUE.

2.2Arrays
Arraysareprecededwithan"at"sigil.The"@"isastylized"a".Anarraystoresabunchof
scalarsthatareaccessedviaanintegerindex.PerlarraysareONEDIMENSIONALONLY.
(DoNotPanic.)ThefirstelementofanarrayalwaysstartsatZERO(0).Whenyourefertoan
entirearray,usethe"@"sigil.
my@numbers=qw(zeroonetwothree)

Whenyouindexintothearray,the"@"characterchangestoa"$"andthenumericindexis
placedinsquarebrackets.
my@numbers=qw(zeroonetwothree)
my$string=$numbers[2]
warn$string
>two...

Thelengthofanarrayisnotpredeclared.Perlautovivifieswhateverspaceitneeds.
my@months
$months[1]='January'
$months[5]='May'
#$months[0]and$months[2..4]areautovivified
#andinitializedtoundef
printDumper\@months
>$VAR1=[

>undef,#index0isundefined
>'January',#$months[1]
>${\$VAR1>[0]},#thisissameasundef
>${\$VAR1>[0]},#undef
>${\$VAR1>[0]},#undef
>'May'#$months[5]
>]

Ifyouwanttoseeifyoucanblowyourmemory,tryrunningthispieceofcode:
my@mem_hog
$mem_hog[10000000000000000000000]=1
#thearrayisfilledwithundefs
#exceptthelastentry,whichisinitializedto1

ArrayscanstoreANYTHINGthatcanbestoredinascalar
my@junk_drawer=('pliers',1,1,1,'*','//',
3.14,9*11,'yaba','daba')

Negativeindexesstartfromtheendofthearrayandworkbackwards.
my@colors=qw(redgreenblue)
my$last=$colors[1]
warn"lastis'$last'"
>lastis'blue'...

2.2.1scalar(@array)
Togethowmanyelementsareinthearray,use"scalar"
my@phonetic=qw(alphabravocharliedelta)
my$quantity=scalar(@phonetic)
warn$quantity

>4...

Whenyouassignanentirearrayintoascalarvariable,youwillgetthesamething,butcalling
scalar()ismuchmoreclear.
my@phonetic=qw(alphabravocharlie)
my$quant=@phonetic
warn$quant
>3...

Thisisexplainedlaterinthe"listcontext"section.

2.2.2push(@array,LIST)
Usepush()toaddelementsontotheendofthearray(thehighestindex).Thiswillincrease
thelengthofthearraybythenumberofitemsadded.
my@groceries=qw(milkbread)
push(@groceries,qw(eggsbaconcheese))
printDumper\@groceries
>$VAR1=[
>'milk',
>'bread',
>'eggs',
>'bacon',
>'cheese'
>]

2.2.3pop(@array)
Usepop()togetthelastelementoffoftheendofthearray(thehighestindex).Thiswill
shortenthearraybyone.Thereturnvalueofpop()isthevaluepoppedoffofthearray.
my@names=qw(alicebobcharlie)

my$last_name=pop(@names)
warn"popped=$last_name"
printDumper\@names
>popped=charlie...
>$VAR1=[
>'alice',
>'bob'
>]

2.2.4shift(@array)
Useshift()toremoveoneelementfromthebeginning/bottomofanarray(i.e.atindexzero).
AllelementswillbeshiftedDOWNoneindex.Thearraywillbeshortedbyone.Thereturn
valueisthevalueremovedfromthearray.
my@curses=qw(feefiefoefum)
my$start=shift(@curses)
warn$start
warnDumper\@curses
>fee
>$VAR1=[
>'fie',
>'foe',
>'fum'
>]

2.2.5unshift(@array,LIST)
useunshift()toaddelementstotheBEGINNING/BOTTOMofanarray(i.e.atindexZERO).
Alltheotherelementsinthearraywillbeshifteduptomakeroom.Thiswilllengththearray

bythenumberofelementsinLIST.
my@trees=qw(pinemapleoak)
unshift(@trees,'birch')
warnDumper\@trees
>$VAR1=[
>'birch',#index0
>'pine',#oldindex0,now1
>'maple',#2
>'oak'#3
>]

2.2.6foreach(@array)
Useforeachtoiteratethroughalltheelementsofalist.Itsformaldefinitionis:
LABELforeachVAR(LIST)BLOCK

Thisisacontrolflowstructurethatiscoveredinmoredetailinthe"controlflow"section.The
foreachstructuresupportslast,next,andredostatements.Useasimpleforeachlooptodo
somethingtoeachelementinanarray:
my@fruits=qw(applesorangeslemonspears)
foreachmy$fruit(@fruits){
print"fruitis'$fruit'\n"
}
>fruitis'apples'
>fruitis'oranges'
>fruitis'lemons'
>fruitis'pears'

DONOTADDORDELETEELEMENTSTOANARRAYBEINGPROCESSEDIN

AFOREACHLOOP.
my@numbers=qw(zeroonetwothree)
foreachmy$num(@numbers){
shift(@numbers)if($numeq'one')
print"numis'$num'\n"
}
>numis'zero'
>numis'one'
>numis'three'
#note:Ideleted'zero',butIfailedto
#printout'two',whichisstillpartofarray.
#BAD!!

VARactsasanaliastotheelementofthearrayitself.ChangestoVARpropagateto
changingthearray.
my@integers=(23,142,9384,83948)
foreachmy$num(@integers){
$num+=100
}
printDumper\@integers
>$VAR1=[
>123,
>242,
>9484,
>84048

>]

2.2.7sort(@array)
Usesort()tosortanarrayalphabetically.Thereturnvalueisthesortedversionofthearray.
Thearraypassedinisleftuntouched.
my@fruit=qw(pearsapplesbananasoranges)
my@sorted_array=sort(@fruit)
printDumper\@sorted_array
>$VAR1=[
>'apples',
>'bananas',
>'oranges',
>'pears'
>]

Sortingalistofnumberswillsortthemalphabeticallyaswell,whichprobablyisnotwhatyou
want.
my@scores=(1000,13,27,200,76,150)
my@sorted_array=sort(@scores)
printDumper\@sorted_array
>$VAR1=[
>1000,#1's
>13,#1's
>150,#1's
>200,
>27,
>76

>]

Thesort()functioncanalsotakeacodeblock(anypieceofcodebetweencurlybraces)
whichdefineshowtoperformthesortifgivenanytwoelementsfromthearray.Thecode
blockusestwoglobalvariables,$aand$b,anddefineshowtocomparethetwoentries.This
ishowyouwouldsortanarraynumerically.
my@scores=(1000,13,27,200,76,150)
my@sorted_array=sort{$a<=>$b}(@scores)
printDumper\@sorted_array
>$VAR1=[
>13,
>27,
>76,
>150,
>200,
>1000
>]

2.2.8reverse(@array)
Thereverse()functiontakesalistandreturnsanarrayinreverseorder.Thelastelement
becomesthefirstelement.Thefirstelementbecomesthelastelement.
my@numbers=reverse(1000,13,27,200,76,150)
printDumper\@numbers
>$VAR1=[
>150,
>76,
>200,

>27,
>13,
>1000
>]

2.2.9splice(@array)
Usesplice()toaddorremoveelementsintooroutofanyindexrangeofanarray.
splice(ARRAY,OFFSET,LENGTH,LIST)

TheelementsinARRAYstartingatOFFSETandgoingforLENGTHindexeswillberemoved
fromARRAY.AnyelementsfromLISTwillbeinsertedatOFFSETintoARRAY.
my@words=qw(hellothere)
splice(@words,1,0,'out')
warnjoin("",@words)
>hellooutthere...

2.2.10UndefinedandUninitializedArrays
Anarrayisinitializedashavingnoentries.Thereforeyoucantesttoseeifanarrayis
initializedbycallingscalar()onit.Thisisequivalenttocallingdefined()onascalarvariable.If
scalar()returnsfalse(i.e.integer0),thenthearrayisuninitialized.Ifyouwanttouninitialize
anarraythatcontainsdata,thenyoudoNOTwanttoassignitundeflikeyouwouldascalar.
Thiswouldfillthearraywithoneelementatindexzerowithavalueofundefined.
my@array=undef#WRONG

Toclearanarraytoitsoriginaluninitializedstate,assignanemptylisttoit.Thiswillclearout
anyentries,andleaveyouwithacompletelyemptyarray.
my@array=()#RIGHT

2.3Hashes
Hashesareprecededwithapercentsignsigil.The"%"isastylized"key/value"pair.Ahash
storesabunchofscalarsthatareaccessedviaastringindexcalleda"key"Perlhashesare
ONEDIMENSIONALONLY.(DoNotPanic.)Thereisnoordertotheelementsinahash.

(Well,thereis,butyoushouldnotuseahashwithanassumptionaboutwhatorderthedata
willcomeout.)Youcanassignanyevennumberofscalarstoahash.Perlwillextractthemin
pairs.Thefirstitemwillbetreatedasthekey,andtheseconditemwillbetreatedasthe
value.Whenyourefertoanentirehash,usethe"%"sigil.
my%info=qw(nameJohnage42)

Whenyoulookupakeyinthehash,the"%"characterchangestoa"$"andthekeyis
placedincurlybraces.
my%info=qw(nameJohnage42)
my$data=$info{name}
warn$data
>John...

Thekeysofahasharenotpredeclared.IfthekeydoesnotexistduringanASSIGNMENT,
thekeyiscreatedandgiventheassignedvalue.
my%inventory
$inventory{apples}=42
$inventory{pears}=17
$inventory{bananas}=5
printDumper\%inventory
>$VAR1={
>'bananas'=>5,
>'apples'=>42,
>'pears'=>17
>}

IfthekeydoesnotexistduringaFETCH,thekeyisNOTcreated,andundefisreturned.
my%inventory
$inventory{apples}=42

my$peaches=$inventory{peaches}
warn"peachesis'$peaches'"
printDumper\%inventory
>Useofuninitializedvalueinconcatenation
>peachesis''at./test.plline13.
>$VAR1={
>'apples'=>42
>}

2.3.1exists($hash{$key})
Useexists()toseeifakeyexistsinahash.Youcannotsimplytestthevalueofakey,sincea
keymightexistbutstoreavalueofFALSE
my%pets=(cats=>2,dogs=>1)
unless(exists($pets{fish})){
print"Nofishhere\n"
}

Warning:duringmultikeylookup,allthelowerlevelkeysareautovivified,andonlythelast
keyhasexists()testedonit.Thisonlyhappensifyouhaveahashofhashreferences.
Referencesarecoveredlater,butthisisa"feature"specifictoexists()thatcanleadtovery
subtlebugs.Noteinthefollowingexample,weexplicitlycreatethekey"Florida",butweonly
testfortheexistenceof{Maine}>{StateBird},whichhasthesideeffectofcreatingthekey
{Maine}inthehash.
my%stateinfo
$stateinfo{Florida}>{Abbreviation}='FL'
if(exists($stateinfo{Maine}>{StateBird})){
warn"itexists"
}

printDumper\%stateinfo
>$VAR1={
>'Florida'=>{
>'Abbreviation'=>'FL'
>},
>'Maine'=>{}
>}

Youmusttesteachlevelofkeyindividually,andbuildyourwayuptothefinalkeylookupif
youdonotwanttoautovivifythelowerlevelkeys.
my%stateinfo
$stateinfo{Florida}>{Abbreviation}='FL'
if(exists($stateinfo{Maine})){
if(exists($stateinfo{Maine}>{StateBird}))
{warn"itexists"}
}
printDumper\%stateinfo
>$VAR1={
>'Florida'=>{
>'Abbreviation'=>'FL'
>}
>}

2.3.2delete($hash{key})
Usedeletetodeleteakey/valuepairfromahash.Onceakeyiscreatedinahash,assigning
undeftoitwillkeepthekeyinthehashandwillonlyassignthevaluetoundef.Theonlyway
toremoveakey/valuepairfromahashiswithdelete().

my%pets=(
fish=>3,
cats=>2,
dogs=>1,
)
$pets{cats}=undef
delete($pets{fish})
printDumper\%pets
>$VAR1={
>'cats'=>undef,
>'dogs'=>1
>}

2.3.3keys(%hash)
Usekeys()toreturnalistofallthekeysinahash.Theorderofthekeyswillbebasedonthe
internalhashingalgorithmused,andshouldnotbesomethingyourprogramdependsupon.
Noteintheexamplebelowthattheorderofassignmentisdifferentfromtheorderprintedout.
my%pets=(
fish=>3,
cats=>2,
dogs=>1,
)
foreachmy$pet(keys(%pets)){
print"petis'$pet'\n"
}

>petis'cats'
>petis'dogs'
>petis'fish'

Ifthehashisverylarge,thenyoumaywishtousetheeach()functiondescribedbelow.

2.3.4values(%hash)
Usevalues()toreturnalistofallthevaluesinahash.Theorderofthevalueswillmatchthe
orderofthekeysreturninkeys().
my%pets=(
fish=>3,
cats=>2,
dogs=>1,
)
my@pet_keys=keys(%pets)
my@pet_vals=values(%pets)
printDumper\@pet_keys
printDumper\@pet_vals
>$VAR1=[
>'cats',
>'dogs',
>'fish'
>]
>$VAR1=[
>2,
>1,

>3
>]

Ifthehashisverylarge,thenyoumaywishtousetheeach()functiondescribedbelow.

2.3.5each(%hash)
Useeach()toiteratethrougheachkey/valuepairinahash,oneatatime.
my%pets=(
fish=>3,
cats=>2,
dogs=>1,
)
while(my($pet,$qty)=each(%pets)){
print"pet='$pet',qty='$qty'\n"
}
>pet='cats',qty='2'
>pet='dogs',qty='1'
>pet='fish',qty='3'

Everycalltoeach()returnsthenextkey/valuepairinthehash.Afterthelastkey/valuepairis
returned,thenextcalltoeach()willreturnanemptylist,whichisbooleanfalse.Thisishow
thewhileloopisabletoloopthrougheachkey/valueandthenexitwhendone.Everyhash
hasone"eachiterator"attachedtoit.Thisiteratorisusedbyperltorememberwhereitisin
thehashforthenextcalltoeach().Callingkeys()onthehashwillresettheiterator.Thelist
returnedbykeys()canbediscarded.
keys(%hash)

Donotaddkeyswhileiteratingahashwitheach().Youcandeletekeyswhileiteratingahash
witheach().Theeach()functiondoesnothavetobeusedinsideawhileloop.Thisexample
usesasubroutinetocalleach()onceandprintouttheresult.Thesubroutineiscalled

multipletimeswithoutusingawhile()loop.
my%pets=(
fish=>3,
cats=>2,
dogs=>1,
)
subone_time{
my($pet,$qty)=each(%pets)
#ifkeyisnotdefined,
#theneach()musthavehitendofhash
if(defined($pet)){
print"pet='$pet',qty='$qty'\n"
}else{
print"endofhash\n"
}
}
one_time#cats
one_time#dogs
keys(%pets)#resetthehashiterator
one_time#cats
one_time#dogs
one_time#fish
one_time#endofhash
one_time#cats

one_time#dogs
>pet='cats',qty='2'
>pet='dogs',qty='1'
>pet='cats',qty='2'
>pet='dogs',qty='1'
>pet='fish',qty='3'
>endofhash
>pet='cats',qty='2'
>pet='dogs',qty='1'

Thereisonlyoneiteratorvariableconnectedwitheachhash,whichmeanscallingeach()on
ahashinaloopthatthencallseach()onthesamehashanotherloopwillcauseproblems.
Theexamplebelowgoesthroughthe%petshashandattemptstocomparethequantityof
differentpetsandprintouttheircomparison.
my%pets=(
fish=>3,
cats=>2,
dogs=>1,
)
while(my($orig_pet,$orig_qty)=each(%pets)){
while(my($cmp_pet,$cmp_qty)=each(%pets)){
if($orig_qty>$cmp_qty){
print"therearemore$orig_pet"
."than$cmp_pet\n"
}else{
print"thereareless$orig_pet"

."than$cmp_pet\n"
}
}
}
>therearemorecatsthandogs
>therearelesscatsthanfish
>therearemorecatsthandogs
>therearelesscatsthanfish
>therearemorecatsthandogs
>therearelesscatsthanfish
>therearemorecatsthandogs
>therearelesscatsthanfish
>...

Theoutsideloopcallseach()andgets"cats".Theinsideloopcallseach()andgets"dogs".
Theinsideloopcontinues,callseach()again,andgets"fish".Theinsideloopcallseach()
onemoretimeandgetsanemptylist.Theinsideloopexits.Theoutsideloopcallseach()
whichcontinueswheretheinsideloopleftoff,namelyattheendofthelist,andreturns
"cats".Thecodethenenterstheinsideloop,andtheprocessrepeatsitselfindefinitely.
Onesolutionforthiseach()limitationisshownbelow.Theinnerloopcontinuestocalleach()untilit
getsthekeythatmatchestheouterloopkey.Theinnerloopmustskiptheendofthehash(an
undefinedkey)andcontinuetheinnerloop.Thisalsofixesaproblemintheaboveexampleinthatwe
probablydonotwanttocompareakeytoitself.
my%pets=(
fish=>3,
cats=>2,
dogs=>1,

)
while(my($orig_pet,$orig_qty)=each(%pets)){
while(1){
my($cmp_pet,$cmp_qty)=each(%pets)
nextunless(defined($cmp_pet))
lastif($cmp_peteq$orig_pet)
if($orig_qty>$cmp_qty){
print"therearemore$orig_pet"
."than$cmp_pet\n"
}else{
print"thereareless$orig_pet"
."than$cmp_pet\n"
}
}
}
>therearemorecatsthandogs
>therearelesscatsthanfish
>therearelessdogsthanfish
>therearelessdogsthancats
>therearemorefishthancats
>therearemorefishthandogs

Ifyoudonotknowtheouterloopkey,eitherbecauseitsinsomeoneelse'scodeandtheydonotpassit
toyou,orsomesimilarproblem,thentheonlyothersolutionistocallkeysonthehashforallinner
loops,storethekeysinanarray,andloopthroughthearrayofkeysusingforeach.Theinnerloopwill

thennotrelyontheinternalhashiteratorvalue.

2.4ListContext
Listcontextisaconceptbuiltintothegrammarofperl.Youcannotdeclarea"listcontext"in
perlthewayyoumightdeclarean@arrayor%hash.Listcontextaffectshowperlexecutes
yoursourcecode.Hereisanexample.
my@cart1=qw(milkbreadbutter)
my@cart2=qw(eggsbaconjuice)
my@checkout_counter=(@cart1,@cart2)
printDumper\@checkout_counter
>$VAR1=[
>'milk',
>'bread',
>'butter',
>'eggs',
>'bacon',
>'juice'
>]

Basically,twopeoplewithgrocerycarts,@cart1and@cart2,pulleduptothe
@checkout_counterandunloadedtheircartswithoutputtingoneofthoseseparatorbarsin
betweenthem.Thepersonbehindthe@checkout_counterhasnoideawhosegroceriesare
whose.Everythinginlistcontextgetsreducedtoanorderedseriesofscalars.Theoriginal
containerthatheldthescalarsisforgotten.Intheaboveexampletheorderofscalarsis
retained:milk,bread,butteristheorderofscalarsin@cart1andtheorderofthescalarsat
thebeginningof@checkout_counter.However,lookingatjust@checkout_counter,thereis
nowaytoknowwherethecontentsof@cart1endandthecontentsof@cart2begin.Infact,
@cart1mighthavebeenempty,andallthecontentsof@checkout_countercouldbelongto
@cart2,butthereisnowaytoknow.Sometimes,listcontextcanbeextremelyhandy.We

haveusedlistcontextrepeatedlytoinitializearraysandhashesanditworkedaswewould
intuitivelyexpect:
my%pets=(fish=>3,cats=>2,dogs=>1)
my@cart1=qw(milkbreadeggs)

Theinitialvaluesforthehashgetconvertedintoanorderedlistofscalars
('fish',3,'cats',2,'dogs',1)

Thesescalarsarethenusedinlistcontexttoinitializethehash,usingthefirstscalarasakey
andthefollowingscalarasitsvalue,andsoonthroughoutthelist.Listcontextapplies
anytimedataispassedaroundinperl.Scalars,arrays,andhashesareallaffectedbylist
context.Intheexamplebelow,@houseisintendedtocontainalistofalltheitemsinthe
house.However,becausethe%petshashwasreducedtoscalarsinlistcontext,thevalues
3,2,1aredisassociatedfromtheirkeys.The@housevariableisnotveryuseful.
my%pets=(fish=>3,cats=>2,dogs=>1)
my@refrigerator=qw(milkbreadeggs)
my@house=('couch',%pets,@refrigerator,'chair')
printDumper\@house
>$VAR1=[
>'couch',
>'cats',
>2,
>'dogs',
>1,
>'fish',
>3,
>'milk',
>'bread',

>'eggs',
>'chair'
>]

Therearetimeswhenlistcontextonahashdoesmakesense.
my%encrypt=(tank=>'turtle',bomber=>'eagle')
my%decrypt=reverse(%encrypt)
printDumper\%decrypt
>$VAR1={
>'eagle'=>'bomber',
>'turtle'=>'tank'
>}

The%encrypthashcontainsahashlookuptoencryptplaintextintocyphertext.Anytimeyou
wanttousetheword"bomber",youactuallysendtheword"eagle".Thedecryptionisthe
opposite.Anytimeyoureceivetheword"eagle"youneedtotranslatethattotheword
"bomber".Usingthe%encrypthashtoperformdecryptionwouldrequirealoopthatcalled
each()onthe%encrypthash,loopinguntilitfoundthevaluethatmatchedthewordreceived
overtheradio.Thiscouldtaketoolong.Instead,becausethereisnooverlapbetweenkeys
andvalues,(twodifferentwordsdon'tencrypttothesameword),wecansimplytreatthe
%encrypthashasalist,callthearrayreverse()functiononit,whichflipsthelistaroundfrom
endtoend,andthenstorethatreversedlistintoa%decrypthash.

2.5References
Referencesareathingthatrefer(point)tosomethingelse.The"somethingelse"iscalledthe
"referent",thethingbeingpointedto.Takingareferenceandusingittoaccessthereferentis
called"dereferencing".Agoodrealworldexampleisadriver'slicense.Yourlicense"points"to
whereyoulivebecauseitlistsyourhomeaddress.Yourlicenseisa"reference".The
"referent"isyourhome.Andifyouhaveforgottenwhereyoulive,youcantakeyourlicense
and"dereferencing"ittogetyourselfhome.Itispossiblethatyouhaveroommates,which

wouldmeanmultiplereferencesexisttopointtothesamehome.Buttherecanonlybeone
homeperaddress.Inperl,referencesarestoredinscalars.Youcancreateareferenceby
creatingsomedata(scalar,array,hash)andputtinga"\"infrontofit.
my%home=(
fish=>3,cats=>2,dogs=>1,
milk=>1,bread=>2,eggs=>12,
)
my$license_for_alice=\%home
my$license_for_bob=\%home

AliceandBobareroommatesandtheirlicensesarereferencestothesame%home.This
meansthatAlicecouldbringinabunchofnewpetsandBobcouldeatthebreadoutofthe
refrigeratoreventhoughAlicemighthavebeentheonetoputitthere.Todothis,Aliceand
Bobneedtodereferencetheirlicensesandgetintotheoriginal%homehash.
${$license_for_alice}{dogs}+=5
delete(${$license_for_bob}{milk})
printDumper\%home
>$VAR1={
>'eggs'=>12,
>'cats'=>2,
>'bread'=>2,
>'dogs'=>6,
>'fish'=>3
>}

2.5.1NamedReferents
Areferentisanyoriginaldatastructure:ascalar,array,orhash.Below,wedeclaresome
namedreferents:age,colors,andpets.

my$age=42
my@colors=qw(redgreenblue)
my%pets=(fish=>3,cats=>2,dogs=>1)

2.5.2ReferencestoNamedReferents
Areferencepointstothereferent.Totakeareferencetoanamedreferent,puta"\"infrontof
thenamedreferent.
my$ref_to_age=\$age
my$r_2_colors=\@colors
my$r_pets=\%pets

2.5.3Dereferencing
Todereference,placethereferenceincurlybracesandprefixitwiththesigilofthe
appropriatetype.Thiswillgiveaccesstotheentireoriginalreferent.
${$ref_to_age}++#happybirthday
pop(@{$r_2_colors})
my%copy_of_pets=%{$r_pets}
print"ageis'$age'\n"
>ageis'43'

Ifthereisnoambiguityindereferencing,thecurlybracesarenotneeded.
$$ref_to_age++#anotherbirthday
print"ageis'$age'\n"
>ageis'44'

Itisalsopossibletodereferenceintoanarrayorhashwithaspecificindexorkey.
my@colors=qw(redgreenblue)
my%pets=(fish=>3,cats=>2,dogs=>1)
my$r_colors=\@colorsmy$r_pets=\%pets

${$r_pets}{dogs}+=5
${$r_colors}[1]='yellow'
printDumper\@colorsprintDumper\%pets
>$VAR1=[
'red',
'yellow',#greenturnedtoyellow
'blue'
]
$VAR1={
'cats'=>2,
'dogs'=>6,#5newdogs
'fish'=>3
}

Becausearrayandhashreferentsaresocommon,perlhasashorthandnotationforindexing
intoanarrayorlookingupakeyinahashusingareference.Takethereference,followitby
">",andthenfollowthatbyeither"[index]"or"{key}".This:
${$r_pets}{dogs}+=5
${$r_colors}[1]='yellow'

isexactlythesameasthis:
$r_pets>{dogs}+=5
$r_colors>[1]='yellow'

2.5.4AnonymousReferents
Herearesomereferentsnamedage,colors,andpets.Eachnamedreferenthasareference
toitaswell.
my$age=42

my@colors=qw(redgreenblue)
my%pets=(fish=>3,cats=>2,dogs=>1)
my$r_age=\$age
my$r_colors=\@colors
my$r_pets=\%pets

ItisalsopossibleinperltocreateanANONYMOUSREFERENT.Ananonymousreferenthas
nonamefortheunderlyingdatastructureandcanonlybeaccessedthroughthereference.To
createananonymousarrayreferent,putthecontentsofthearrayinsquarebrackets.The
squarebracketswillcreatetheunderlyingarraywithnoname,andreturnareferencetothat
unnamedarray.
my$colors_ref=['red','green','blue']
printDumper$colors_ref
>$VAR1=[
>'red',
>'green',
>'blue'
>]

Tocreateananonymoushashreferent,putthecontentsofthehashincurlybraces.The
curlybraceswillcreatetheunderlyinghashwithnoname,andreturnareferencetothat
unnamedhash.
my$pets_ref={fish=>3,cats=>2,dogs=>1}
printDumper$pets_ref
>$VAR1={
>'cats'=>2,
>'dogs'=>1,
>'fish'=>3

>}

Notethat$colors_refisareferencetoanarray,butthatarrayhasnonametodirectlyaccessitsdata.
Youmustuse$colors_reftoaccessthedatainthearray.Likewise,$pets_refisareferencetoahash,
butthathashhasnonametodirectlyaccessitsdata.Youmustuse$pets_reftoaccessthedatainthe
hash.

2.5.5ComplexDataStructures
Arraysandhashescanonlystorescalarvalues.Butbecausescalarscanholdreferences,complexdata
structuresarenowpossible.Usingreferencesisonewaytoavoidtheproblemsassociatedwithlist
context.Hereisanotherlookatthehouseexample,butnowusingreferences.
my%pets=(fish=>3,cats=>2,dogs=>1)
my@refrigerator=qw(milkbreadeggs)
my$house={
pets=>\%pets,
refrigerator=>\@refrigerator
}
printDumper$house
>$VAR1={
>'pets'=>{
>'cats'=>2,
>'dogs'=>1,
>'fish'=>3
>},
>'refrigerator'=>[
>'milk',
>'bread',

>'eggs'
>]
>}

The$housevariableisareferencetoananonymoushash,whichcontainstwokeys,"pets"
and"refrigerator".Thesekeysareassociatedwithvaluesthatarereferencesaswell,onea
hashreferenceandtheotheranarrayreference.Dereferencingacomplexdatastructurecan
bedonewiththearrownotationorbyenclosingthereferenceincurlybracesandprefixingit
withtheappropriatesigil.
#Aliceaddedmorecanines
$house>{pets}>{dogs}+=5
#Bobdrankallthemilk
shift(@{$house>{refrigerator}})
2.5.5.1Autovivification

Perlautovivifiesanystructureneededwhenassigningorfetchingfromareference.The
autovivifiedreferentsareanonymous.Perlwillassumeyouknowwhatyouaredoingwith
yourstructures.Intheexamplebelow,westartoutwithanundefinedscalarcalled$scal.We
thenfetchfromthisundefinedscalar,asifitwereareferencetoanarrayofahashofan
arrayofahashofanarray.Perlautovivifieseverythingundertheassumptionthatthatiswhat
youwantedtodo.
my$scal
my$val=
$scal>[2]>{somekey}>[1]>{otherkey}>[1]
printDumper$scal
>$VAR1=[
>undef,
>${\$VAR1>[0]},
>{

>'somekey'=>[
>${\$VAR1>[0]},
>{
>'otherkey'=>[]
>}
>]
>}
>]

IfthisisNOTwhatyouwanttodo,checkfortheexistenceofeachhashkeyandcheckthat
thearraycontainsatleastenougharrayentriestohandlethegivenindex.
2.5.5.2MultidimensionalArrays

Perlimplementsmultidimensionalarraysusingonedimensionalarraysandreferences.
my$mda
for(my$i=0$i<2$i++){
for(my$j=0$j<2$j++){
for(my$k=0$k<2$k++){
$mda>[$i]>[$j]>[$k]=
"row=$i,col=$j,depth=$k"
}
}
}
printDumper$mda
>$VAR1=[
>[

>[
>'row=0,col=0,depth=0',
>'row=0,col=0,depth=1'
>],
>[
>'row=0,col=1,depth=0',
>'row=0,col=1,depth=1'
>]
>],
>[
>[
>'row=1,col=0,depth=0',
>'row=1,col=0,depth=1'
>],
>[
>'row=1,col=1,depth=0',
>'row=1,col=1,depth=1'
>]
>]
>]
2.5.5.3DeepCloning,DeepCopy

Ifyouneedtocreateanentirelyseparatebutidenticalcloneofacomplexdatastructure,use
theStorable.pmperlmodule.Storablecomesstandardwithperl5.8.Ifyoudon'thave5.8
installed,consideranupgrade.Otherwise,readthesectionaboutCPANlaterinthis

document,downloadStorablefromCPAN,andinstall.ThenuseStorableinyourperlcode,
indicatingyouwanttoimportthe'nstore','dclone',and'retrieve'subroutines.The'use'
statementisexplainedlaterinthisdocumentaswell,fornow,itisn'tthatimportant.The
'dclone'subroutinetakesareferencetoanykindofdatastructureandreturnsareferenceto
adeepclonedversionofthatdatastructure.
useStorableqw(nstoredcloneretrieve)
my$scal
$scal>[2]>{somekey}>[1]>{otherkey}>[1]
#$twinisanidenticalcloneof$scal
my$twin=dclone$scal
2.5.5.4DataPersistence

TheStorable.pmmodulealsocontainstwosubroutinesforstoringthecontentsofanyperl
datastructuretoafileandretrievingitlater.
useStorableqw(nstoredcloneretrieve)
my$scal
$scal>[2]>{somekey}>[1]>{otherkey}>[1]
nstore($scal,'filename')
#exit,rebootcomputer,andrestartscript
my$revived=retrieve('filename')

2.5.6StringificationofReferences
Perlwillstringifyareferenceifyoutrytodoanythingstringlikewithit,suchasprintit.
my$referent=42
my$reference=\$referent
warn"referenceis'$reference'"
>referenceis'SCALAR(0x812e6ec)'...

Butperlwillnotallowyoutocreateastringandattempttoturnitintoareference.

my$reference='SCALAR(0x812e6ec)'
my$value=$$reference
>Can'tusestring("SCALAR(0x812e6ec)")as
>aSCALARrefwhile"strictrefs"inuse

Turningstrictoffonlygivesyouundef.
nostrict
my$reference='SCALAR(0x812e6ec)'
my$value=$$reference
warn"valuenotdefined"unless(defined($value))
warn"valueis'$value'\n"
>valuenotdefined
>Useofuninitializedvalueinconcatenation

Becauseareferenceisalwaysastringthatlookssomethinglike"SCALAR(0x812e6ec)",it
willevaluatetruewhentreatedasaboolean,evenifthevaluetowhichitpointsisfalse.

2.5.7Theref()function
Theref()functiontakesascalarandreturnsastringindicatingwhatkindofreferentthe
scalarisreferencing.Ifthescalarisnotareference,ref()returnsfalse(anemptystring).
my$temp=\42
my$string=ref($temp)
warn"stringis'$string'"
>stringis'SCALAR'

Herewecallref()onseveraltypesofvariable:
subwhat_is_it{
my($scalar)=@_
my$string=ref($scalar)

print"stringis'$string'\n"
}
what_is_it(\'hello')
what_is_it([1,2,3])
what_is_it({cats=>2})
what_is_it(42)
>stringis'SCALAR'
>stringis'ARRAY'
>stringis'HASH'
>stringis''

Notethatthisislikestringificationofareferenceexceptwithouttheaddressbeingpartofthe
string.InsteadofSCALAR(0x812e6ec),itsjustSCALAR.Alsonotethatifyoustringifyanon
reference,yougetthescalarvalue.Butifyoucallref()onanonreference,yougetanempty
string,whichisalwaysfalse.

3ControlFlow
Standardstatementsgetexecutedinsequentialorderinperl.
my$name='JohnSmith'
my$greeting="Hello,$name\n"
print$greeting

Controlflowstatementsallowyoutoaltertheorderofexecutionwhiletheprogramisrunning.
if($price==0){
print"FreeBeer!\n"
}

Perlsupportsthefollowingcontrolflowstructures:
##

LABELisanoptionalnamethatidentifiesthe
#controlflowstructure.
#Itisabarewordidentifierfollowedbyacolon.
#example==>MY_NAME:
##
SINGLE_STATEMENT==>asingleperlstatement
#NOTincludingthesemicolon.
#print"hello\n"
##
BLOCK==>zeroormorestatementscontained
#incurlybraces{print"hi"}
LABELBLOCK
LABELBLOCKcontinueBLOCK
#BOOL==>boolean(seebooleansectionabove)
SINGLE_STATEMENTif(BOOL)
if(BOOL)BLOCK
if(BOOL)BLOCKelseBLOCK
if(BOOL)BLOCKelsif(BOOL)BLOCKelsif()...
if(BOOL)BLOCKelsif(BOOL)BLOCK...elseBLOCK
unless(BOOL)BLOCK
unless(BOOL)BLOCKelseBLOCK
unless(BOOL)BLOCKelsif(BOOL)BLOCKelsif()...
unless(BOOL)BLOCKelsif(BOOL)BLOCK...else

BLOCK
LABELwhile(BOOL)BLOCK
LABELwhile(BOOL)BLOCKcontinueBLOCK
LABELuntil(BOOL)BLOCK
LABELuntil(BOOL)BLOCKcontinueBLOCK
#INIT,TEST,CONTareallexpressions
#INITisaninitializationexpression
#INITisevaluatedoncepriortoloopentry
#TESTisBOOLEANexpressionthatcontrolsloopexit
#TESTisevaluatedeachtimeafter
#BLOCKisexecuted
#CONTisacontinuationexpression
#CONTisevaluatedeachtimeTESTisevaluatedTRUE
LABELfor(INITTESTCONT)BLOCK
#LISTisalistofscalars,seearraysand
#listcontextsectionslaterintext
LABELforeach(LIST)BLOCK
LABELforeachVAR(LIST)BLOCK
LABELforeachVAR(LIST)BLOCKcontinueBLOCK

3.1Labels
Labelsarealwaysoptional.Alabelisanidentifierfollowedbyacolon.Alabelisusedtogive
itsassociatedcontrolflowstructureaname.InsideaBLOCKofacontrolflowstructure,you
cancall
next

last
redo

IfthestructurehasaLABEL,youcancall
nextLABEL
lastLABEL
redoLABEL

Ifnolabelisgiventonext,last,orredo,thenthecommandwilloperateontheinnermost
controlstructure.Ifalabelisgiven,thenthecommandwilloperateonthecontrolstructure
given.

3.2lastLABEL
Thelastcommandgoestotheendoftheentirecontrolstructure.Itdoesnotexecuteany
continueblockifoneexists.

3.3nextLABEL
ThenextcommandskipstheremainingBLOCK.ifthereisacontinueblock,execution
resumesthere.Afterthecontinueblockfinishes,orifnocontinueblockexists,execution
startsthenextiterationofthecontrolconstructifitisaloopconstruct.

3.4redoLABEL
TheredocommandskipstheremainingBLOCK.Itdoesnotexecuteanycontinueblock
(evenifitexists).Executionthenresumesatthestartofthecontrolstructurewithout
evaluatingtheconditionalagain.

4PackagesandNamespacesandLexicalScoping
4.1PackageDeclaration
Perlhasapackagedeclarationstatementthatlookslikethis:
packageNAMESPACE

Thispackagedeclarationindicatesthattherestoftheenclosingblock,subroutine,eval,or
filebelongstothenamespacegivenbyNAMESPACE.Thestandardwarnings,strictness,and
Data::Dumperareattachedtothenamespaceinwhichtheywereturnedonwith"use
warnings"etc.Anytimeyoudeclareanewpackagenamespace,youwillwantto"use"these
again.
packageSomeOtherPackage
usewarningsusestrictuseData::Dumper

Allperlscriptsstartwithanimplieddeclarationof:
packagemain

Youcanaccesspackagevariableswiththeappropriatesigil,followedbythepackagename,
followedbyadoublecolon,followedbythevariablename.Thisiscalledapackage
QUALIFIEDvariablemeaningthepackagenameisexplicitlystated.
$package_this::age
@other_package::refrigerator
%package_that::pets

IfyouuseanUNQUALIFIEDvariableinyourcode,perlassumesitisinthethemostrecently
declaredpackagenamespacethatwasdeclared.Whenyouhavestrictnessturnedon,there
aretwowaystocreateandusepackagevariables:1)Usethefullypackagequalifiedname
everywhereinyourcode:
#canusevariablewithoutdeclaringitwith'my'
$some_package::answer=42
warn"Thevalueis'$some_package::answer'\n"

4.2DeclaringPackageVariablesWithour
2)Use"our"todeclarethevariable.
packagethis_package
our$name='John'
warn"nameis'$name'"

Using"our"isthepreferredmethod.Youmusthaveperl5.6.0orlaterfor"our"
declarations.Thedifferencebetweenthetwomethodsisthatalwaysusingpackagequalified
variablenamesmeansyoudoNOThavetodeclarethepackageyouarein.Youcancreate
variablesinANYnamespaceyouwant,withouteverhavingtodeclarethenamespace
explicitly.Youcanevendeclarevariablesinsomeoneelse'spackagenamespace.Thereis
norestrictionsinperlthatpreventyoufromdoingthis.Toencourageprogrammerstoplay
nicewitheachother'snamespaces,the"our"functionwascreated.Declaringavariablewith
"our"willcreatethevariableinthecurrentnamespace.Ifthenamespaceisotherthan
"main",thenyouwillneedtodeclarethepackagenamespaceexplicitly.However,oncea
packagevariableisdeclaredwith"our",thefullypackagequalifiednameisNOTrequired,
andyoucanrefertothevariablejustonitsvariablename,asexample(2)abovereferstothe
$namepackagevariable.WedonotHAVEtousethe"our"shortcutevenifweuseditto
declareit.The"our"declarationisashorthandfordeclaringapackagevariable.Oncethe
packagevariableexists,wecanaccessitanywaywewish.
packageHogs
our$speak='oink'
warn"Hogs::speakis'$Hogs::speak'"
>Hogs::speakis'oink'...

4.3PackageVariablesinsideaLexicalScope
Whenyoudeclareapackageinsideacodeblock,thatpackagenamespacedeclaration
remainsineffectuntiltheendoftheblock,atwhichtime,thepackagenamespacerevertsto
thepreviousnamespace.
packageHogs
our$speak='oink'
{#STARTOFCODEBLOCK
packageHeifers
our$speak='moo'
}#ENDOFCODEBLOCK

warn"speakis'$speak'"
>speakis'oink'...

TheHeifersnamespacestillexists,asdoesallthevariablesthatweredeclaredinthat
namespace.Itsjustthatoutsidethecodeblock,the"ourHeifers"declarationhaswornoff,
andwenowhavetouseafullypackagequalifiednametogettothevariablesinHeifers
package.This"wearingoff"isafunctionofthecodeblockbeinga"lexicalscope"anda
packagedeclarationonlylaststotheendofthecurrentlexicalscope.Thepackagevariables
declaredinsidethecodeblock"survive"afterthecodeblockends.
{
packageHeifers
our$speak='moo'
}
print"Heifers::speakis'$Heifers::speak'\n"
>Heifers::speakis'moo'

4.4LexicalScope
Lexicalreferstowordsortext.Alexicalscopeexistswhileexecutiontakesplaceinsideofa
particularchunkofsourcecode.Intheaboveexamples,the"packageHeifers"onlyexists
insidethecurlybracesofthesourcecode.Outsidethosecurlybraces,thepackage
declarationhasgoneoutofscope,whichisatechnicalwayofsayingits"wornoff".Scope
referstovision,asintelescope.Withinalexicalscope,thingsthathavelexicallimitations
(suchasapackagedeclaration)areonly"visible"insidethatlexicalspace.So"lexicalscope"
referstoanythingthatisvisibleorhasaneffectonlywithingacertainboundaryofthesource
textorsourcecode.Theeasiestwaytodemonstratelexicalscopingislexicalvariables,and
toshowhowlexicalvariablesdifferfrom"our"variables.

4.5LexicalVariables
Lexicalvariablesaredeclaredwiththemykeyword.Lexicalvariablesdeclaredinsidea
lexicalscopedonotsurviveoutsidethelexicalscope.

nowarnings
nostrict
{
my$speak='moo'
}
warn"speakis'$speak'\n"
>speakis''

Thelexicalvariable"$speak"goesoutofscopeattheendofthecodeblock(atthe"}"
character),soitdoesnotexistwhenwetrytoprintitoutaftertheblock.Wehadtoturn
warningsandstrictoffjusttogetittocompilebecausewithwarningsandstricton,perlwill
know$speakdoesnotexistwhenyouattempttoprintit,soitwillthrowanexceptionand
quit.Lexicallyscopedvariableshavethreemainfeatures:1)Lexicalvariablesdonotbelongto
anypackagenamespace,soyoucannotprefixthemwithapackagename.Theexample
belowshowsthatmy$cntisnotthesameasthemain::cnt:
nowarnings
packagemain
my$cnt='Iamjustalexical'
warn"main::cntis'$main::cnt'"
>main::cntis''

2)Lexicalvariablesareonlydirectlyaccessiblefromthepointwheretheyaredeclaredtothe
endofthenearestenclosingblock,subroutine,eval,orfile.
nostrict
{
my$some_lex='Iamlex'
}
warn"some_lexis'$some_lex'"

>some_lexis''

3)Lexicalvariablesaresubjectto"garbagecollection"attheendofscope.Ifnothingisusing
alexicalvariableattheendofscope,perlwillremoveitfromitsmemory.Everytimea
variableisdeclaredwith"my",itiscreateddynamically,duringexecution.Thelocationofthe
variablewillchangeeachtime.Noteintheexamplebelow,wecreateanew$lex_vareach
timethroughtheloop,and$lex_varisatadifferentaddresseachtime.
my@cupboard
for(1..5){
my$lex_var='cannedgoods'
my$lex_ref=\$lex_var
push(@cupboard,$lex_ref)
print"$lex_ref\n"
}
>SCALAR(0x812e770)
>SCALAR(0x812e6c8)
>SCALAR(0x812e6e0)
>SCALAR(0x81624c8)
>SCALAR(0x814cf64)

Lexicalvariablesarejustplaingood.Theygenerallykeepyoufromsteppingonsomeone
else'stoes.Theyalsokeepyourdatamoreprivatethanapackagevariable.Package
variablesarepermanent,nevergooutofscope,nevergetgarbagecollected,andare
accessiblefromanyone'sscript.

4.6GarbageCollection
Whenalexicalvariablegoesoutofscope,perlwillchecktoseeifanyoneisusingthat
variable,andifnooneisusingit,perlwilldeletethatvariableandfreeupmemory.Thefreed
upmemoryisnotreturnedtothesystem,ratherthefreedupmemoryisusedforpossible

declarationsofnewlexicallyscopedvariablesthatcouldbedeclaredlaterinthe
program.Thismeansthatyourprogramwillnevergetsmallerbecauseoflexicalvariables
goingofofscope.Oncethememoryisallocatedforperl,itremainsunderperl'sjurisdiction.
Butperlcanusegarbagecollectedspaceforotherlexicalvariables.Ifalexicalvariableisa
referentofanothervariable,thenthelexicalwillnotbegarbagecollectedwhenitgoesoutof
scope.
nostrict
my$referring_var
{
my$some_lex='Iamlex'
$referring_var=\$some_lex
}
warn"some_lexis'$some_lex'"
warn"referringvarrefersto'$$referring_var'"
>some_lexis''
>referringvarrefersto'Iamlex'

Whenthelexical$some_lexwentoutofscope,wecouldnolongeraccessitdirectly.But
since$referring_varisareferenceto$some_lex,then$some_lexwasnevergarbage
collected,anditretaineditsvalueof"Iamlex".Thedatain$some_lexwasstillaccessible
throughreferring_var.Notethatthenamedvariable$some_lexwentoutofscopeattheend
ofthecodeblockandcouldnotbeaccessedbyname.

4.6.1ReferenceCountGarbageCollection
Perlusesreferencecountbasedgarbagecollection.Itisrudimentaryreferencecounting,so
circularreferenceswillnotgetcollectedevenifnothingpointstothecircle.Theexample
belowshowstwovariablesthatrefertoeachotherbutnothingreferstothetwovariables.
Perlwillnotgarbagecollectthesevariableseventhoughtheyarecompletelyinaccessibleby
theendofthecodeblock.
{

my($first,$last)
($first,$last)=(\$last,\$first)
}

4.6.2GarbageCollectionandSubroutines
Garbagecollectiondoesnotrelystrictlyonreferencestoavariabletodetermineifitshould
begarbagecollected.Ifasubroutineusesalexicalvariable,thenthatvariablewillnotbe
garbagecollectedaslongasthesubroutineexists.Subroutinesthatusealexicalvariable
declaredoutsideofthesubroutinedeclarationarecalled"CLOSURES".Intheexamplebelow,
thelexicalvariable,$cnt,isdeclaredinsideacodeblockandwouldnormallygetgarbage
collectedattheendoftheblock.However,twosubroutinesaredeclaredinthatsamecode
blockthatuse$cnt,so$cntisnotgarbagecollected.Since$cntgoesoutofscope,theonly
thingsthatcanaccessitafterthecodeblockarethesubroutines.Notethatareferenceto
$cntisnevertaken,howeverperlknowsthat$cntisneededbythesubroutinesandtherefore
keepsitaround.Theincanddecsubroutinesaresubroutineclosures.
{
my$cnt=0
subinc{$cnt++print"cntis'$cnt'\n"}
subdec{$cntprint"cntis'$cnt'\n"}
}
inc
inc
inc
dec
dec
inc
>cntis'1'

>cntis'2'
>cntis'3'
>cntis'2'
>cntis'1'
>cntis'2'

Subroutinenamesarelikenamesofpackagevariables.Thesubroutinegetsplacedinthe
currentdeclaredpackagenamespace.Therefore,namedsubroutinesarelikepackage
variablesinthat,oncedeclared,theynevergooutofscopeorgetgarbagecollected.

4.7PackageVariablesRevisited
Packagevariablesarenotevil,theyarejustglobalvariables,andtheyinheritallthepossible
problemsassociatedwithusingglobalvariablesinyourcode.IntheeventyouDOendup
usingapackagevariableinyourcode,theydohavesomeadvantages.Theyareglobal,
whichmeanstheycanbeaconvenientwayforseveraldifferentblocksofperlcodetotalk
amongstthemselvesusinganagreeduponglobalvariableastheirchannel.Imagineseveral
subroutinesacrossseveralfilesthatallwanttocheckaglobalvariable:
$Development::Verbose.Ifthisvariableistrue,thesesubroutinesprintdetailedinformation.If
itisfalse,thesesubroutinesprintlittleornoinformation.
packageDevelopment
our$Verbose=1
subCompile{
if($Development::Verbose){
print"compiling\n"}
}
subLink{
if($Development::Verbose){
print"linking\n"

}
}
subRun{
if($Development::Verbose){
print"running\n"
}
}
Compile
Link
Run
>compiling
>linking
>running

Thethreesubroutinescouldbeindifferentfiles,indifferentpackagenamespaces,andthey
couldallaccessthe$Development::Verbosevariableandactaccordingly.

4.8Callinglocal()onPackageVariables
Whenworkingwithglobalvariables,therearetimeswhenyouwanttosavethecurrentvalue
oftheglobalvariable,setittoanewandtemporaryvalue,executesomeforeigncodethat
willaccessthisglobal,andthensettheglobalbacktowhatitwas.Continuingtheprevious
example,saywewishtocreateaRunSilentsubroutinethatstores$Development::Verbosein
atempvariable,callstheoriginalRunroutine,andthensets$Development::Verbosebackto
itsoriginalvalue.
packageDevelopment
our$Verbose=1
subCompile{

if($Development::Verbose){
print"compiling\n"
}
}
subLink{
if($Development::Verbose){
print"linking\n"
}
}
subRun{
if($Development::Verbose){
print"running\n"
}
}
subRunSilent{
my$temp=$Development::Verbose
$Development::Verbose=0
Run
$Development::Verbose=$temp
}
Compile
Link
RunSilent

>compiling
>linking

Thiscanalsobeaccomplishedwiththe"local()"function.Thelocalfunctiontakesapackage
variable,savesofftheoriginalvalue,allowsyoutoassignatempvaluetoit.Thatnewvalue
isseenbyanyoneaccessingthevariable.Andattheendofthelexicalscopeinwhichlocal()
wascalled,theoriginalvalueforthevariableisreturned.TheRunSilentsubroutinecouldbe
writtenlikethis:
subRunSilent{
local($Development::Verbose)=0
Run
}

Perloriginallystartedwithnothingbutpackagevariables.The"my"lexicalvariableswerenot
introduceduntilperlversion4.Sotodealwithallthepackagevariables,perlwasgiventhe
local()function.Localisalsoagoodwaytocreateatemporaryvariableandmakesureyou
don'tsteponsomeoneelse'svariableofthesamename.

5Subroutines
Perlallowsyoutodeclarenamedsubroutinesandanonymoussubroutines,similartotheway
youcandeclarenamedvariablesandanonymousvariables.

5.1SubroutineSigil
Subroutinesusetheampersand(&)astheirsigil.Butwhilethesigilsforscalars,arrays,and
hashesaremandatory,thesigilforsubroutinesisoptional.

5.2NamedSubroutines
Belowisthenamedsubroutinedeclarationsyntax:
subNAMEBLOCK

NAMEcanbeanyvalidperlidentifier.BLOCKisacodeblockenclosedinparenthesis.The

NAMEofthesubroutineisplacedinthecurrentpackagenamespace,inthesameway"our"
variablesgointothecurrentpackagenamespace.Soonceanamedsubroutineisdeclared,
youmayaccessitwithjustNAMEifyouareinthecorrectpackage,orwithafullypackage
qualifiednameifyouareoutsidethepackage.Andyoucanusetheoptionalampersandsigil
ineithercase.
packageMyArea
subPing{print"ping\n"}
Ping
&Ping
MyArea::Ping
&MyArea::Ping
>ping
>ping
>ping
>ping

Oncethecurrentpackagedeclarationchanges,youMUSTuseafullypackagequalified
subroutinenametocallthesubroutine.
packageMyArea
subPing{print"ping\n"}
packageYourArea
MyArea::Ping
&MyArea::Ping
&Ping#error,lookingincurrentpackageYourArea
>ping
>ping
>Undefinedsubroutine&YourArea::Ping

5.3AnonymousSubroutines
Belowistheanonymoussubroutinedeclarationsyntax:
subBLOCK

Thiswillreturnacodereference,similartohow[]returnsanarrayreference,andsimilarto
how{}returnsahashreference.
subwhat_is_it{
my($scalar)=@_
my$string=ref($scalar)
print"refreturned'$string'\n"
}
my$temp=sub{print"Hello\n"}
what_is_it($temp)
>refreturned'CODE'

5.4Data::Dumperandsubroutines
Thecontentsofthecodeblockareinvisibletoanythingoutsidethecodeblock.Forthis
reason,thingslikeData::Dumpercannotlookinsidethecodeblockandshowyoutheactual
code.InsteadData::Dumperdoesnoteventryandjustgivesyouaplaceholderthatreturns
adummystring.
my$temp=sub{print"Hello\n"}
printDumper$temp
>$VAR1=sub{"DUMMY"}

5.5PassingArgumentsto/fromaSubroutine
Anyvaluesyouwanttopasstoasubroutinegetputintheparenthesisatthesubroutinecall.
Fornormalsubroutines,allargumentsgothroughthelistcontextcrushingmachineandget
reducedtoalistofscalars.Theoriginalcontainersarenotknowninsidethesubroutine.The

subroutinewillnotknowifthelistofscalarsitreceivescamefromscalars,arrays,orhashes.
Toavoidsomeofthelistcontextcrushing,asubroutinecanbedeclaredwithaprototype,
whicharediscussedlater.

5.6AccessingArgumentsinsideSubroutinesvia@_
Insidethesubroutine,theargumentsareaccessedviaaspecialarraycalled@_,sinceall
theargumentspassedinwerereducedtolistcontext,theseargumentsfitnicelyintoan
array.The@_arraycanbeprocessedjustlikeanyotherregulararray.Iftheargumentsare
fixedandknown,thepreferredwaytoextractthemistoassign@_toalistofscalarswith
meaningfulnames.
subcompare{
my($left,$right)=@_
return$left<=>$right
}

The@_arrayis"magical"inthatitisreallyalistofaliasesfortheoriginalargumentspassed
in.Therefore,assigningavaluetoanelementin@_willchangethevalueintheoriginal
variablethatwaspassedintothesubroutinecall.Subroutineparametersareeffectively
IN/OUT.
subswap{(@_)=reverse(@_)}
my$one="Iamone"
my$two="Iamtwo"
swap($one,$two)
warn"oneis'$one'"
warn"twois'$two'"
>oneis'Iamtwo'
>twois'Iamone'

Assigningtotheentire@_arraydoesnotwork,youhavetoassigntotheindividual
elements.Ifswapweredefinedlikethis,thevariables$oneand$twowouldremain

unchanged.
subswap{
my($left,$right)=@_
@_=($right,$left)#WRONG
}

5.7DereferencingCodeReferences
Dereferencingacodereferencecausesthesubroutinetobecalled.Acodereferencecanbe
dereferencedbyprecedingitwithanampersandsigilorbyusingthearrowoperatorand
parenthesis">()".Thepreferredwayistousethearrowoperatorwithparens.
my$temp=sub{print"Hello\n"}
&{$temp}
&$temp
$temp>()#preferred
>Hello
>Hello
>Hello

5.8ImpliedArguments
Whencallingasubroutinewiththe"&"sigilprefixandnoparenthesis,thecurrent@_array
getsimplicitlypassedtothesubroutinebeingcalled.Thiscancausesubtlyoddbehaviorif
youarenotexpectingit.
subsecond_level{
printDumper\@_
}
subfirst_level{
#using'&'sigilandnoparens.

#doesn'tlooklikeI'mpassinganyparams
#butperlwillpass@_implicitly.
&second_level
}
first_level(1,2,3)
>$VAR1=[
>1,
>2,
>3
>]

Thisgenerallyisnotaproblemwithnamedsubroutinesbecauseyouprobablywillnotuse
the"&"sigil.However,whenusingcodereferences,dereferencingusingthe"&"maycause
impliedargumentstobepassedtothenewsubroutine.Forthisreason,thearrowoperatoris
thepreferredwaytodereferenceacodereference.
$code_ref>()#passnothing,noimplicit@_
$code_ref>(@_)#explicitlypass@_
$code_ref>('one','two')#passnewparameters

5.9SubroutineReturnValue
Subroutinescanreturnasinglevalueoralistofvalues.Thereturnvaluecanbeexplicit,orit
canbeimpliedtobethelaststatementofthesubroutine.Anexplicitreturnstatementisthe
preferredapproachifanyreturnvalueisdesired.
#returnasinglescalar
subret_scal{
return"boo"
}

my$scal_var=ret_scal
printDumper\$scal_var
#returnalistofvalues
subret_arr{
return(1,2,3)
}
my@arr_var=ret_arr
printDumper\@arr_var
>$VAR1=\'boo'
>$VAR1=[
>1,
>2,
>3
>]

5.10ReturningFalse
Thereturnvalueofasubroutineisoftenusedwithinabooleantest.Theproblemisthatthe
subroutineneedstoknowifitiscalledinscalarcontextorarraycontext.Returningasimple
"undef"value(or0or0.0or"")willworkinscalarcontext,butinarraycontext,itwillcreate
anarraywiththefirstelementsettoundef.Inbooleancontext,anarraywithoneormore
elementsisconsideredtrue.Areturnstatementbyitselfwillreturnundefinscalarcontextand
anemptylistinlistcontext.Thisisthepreferredwaytoreturnfalseinasubroutine.
subthis_is_false{
return#undeforemptylist
}
my$scal_var=this_is_false

my@arr_var=this_is_false

5.11Usingthecaller()FunctioninSubroutines
Thecaller()functioncanbeusedinasubroutinetofindoutinformationaboutwherethe
subroutinewascalledfromandhowitwascalled.Callertakesoneargumentthatindicates
howfarbackinthecallstacktogetitsinformationfrom.Forinformationaboutthecurrent
subroutine,usecaller(0).
subHowWasICalled{
my@info=caller(0)
printDumper\@info
}
HowWasICalled
>$VAR1=[
>'main',
>'./test.pl',
>13,
>'main::HowWasICalled',
>1,
>undef,
>undef,
>undef,
>2,
>'UUUUUUUUUUUU'
>]

Thecaller()functionreturnsalistofinformationinthefollowingorder
0$packagepackagenamespaceattimeofcall

1$filenamefilenamewherecalledoccurred
2$linelinenumberinfilewherecalloccurred
3$subroutinenameofsubroutinecalled
4$hasargstrueifexplicitargumentspassedin
5$wantarraylist=1,scalar=0,void=undef
6$evaltextevaluatedtextifanevalblock
7$is_requiretrueifcreatedby"require"or"use"
8$hintsinternaluseonly,disregard
9$bitmaskinternaluseonly,disregard

Noteintheexampleabove,thecodeisinafilecalledtest.pl.Thecalloccurredinpackage
main,thedefaultpackagenamespace,anditoccurredatline13ofthefile.Thepackage
qualifiednameofthesubroutinethatwascalledwasmain::HowWasICalled.Thepackage
qualifiednamemustbegivensinceyoudon'tknowwhatpackageiscurrentwherethe
subroutinewascalledfrom,thatinformationishiddeninlexicalscope.

5.12Thecaller()functionand$wantarray
Theargumentofinterestisthe$wantarrayargument.Thisindicateswhatreturnvalueis
expectedofthesubroutinefromwhereitwascalled.Thesubroutinecouldhavebeencalled
invoidcontextmeaningthereturnvalueisthrownaway.Oritcouldhavebeencalledandthe
returnvalueassignedtoascalar.Oritcouldhavebeencalledandthereturnvalueassigned
toalistofscalars.
subCheckMyWantArray{
my@info=caller(0)
my$wantarray=$info[5]
$wantarray='undef'unless(defined($wantarray))
print"wantarrayis'$wantarray'\n"
}

CheckMyWantArray#undef
my$scal=CheckMyWantArray#0
my@arr=CheckMyWantArray#1
>wantarrayis'undef'
>wantarrayis'0'
>wantarrayis'1'

5.13ContextSensitiveSubroutineswithwantarray()
Youcanusethewantarrayvariablefromcaller()tocreateasubroutinethatissensitivetothe
contextinwhichitwascalled.
subArrayProcessor{
my@info=caller(0)
my$wantarray=$info[5]
returnunless(defined($wantarray))
if($wantarray){
return@_
}else{
returnscalar(@_)
}
}
my@arr=qw(alphabravocharlie)
ArrayProcessor(@arr)
my$scal=ArrayProcessor(@arr)#3
my@ret_arr=ArrayProcessor(@arr)#alpha...
print"scalis'$scal'\n"

printDumper\@ret_arr
>scalis'3'
>$VAR1=[
>'alpha',
>'bravo',
>'charlie'
>]

6CompilingandInterpreting
Whenperlworksonyoursourcecode,itwillalwaysbeinoneoftwomodes:compilingor
interpreting.Perlhassomehookstoallowaccessintothesedifferentcycles.Theyarecode
blocksthatareprefixedwithBEGIN,CHECK,INIT,andEND.Compiling:translatingthe
sourcetextintomachineusableinternalformat.Interpreting:executingthemachineusable,
internalformat.TheBEGINblockisimmediate.BEGIN>executeblockassoonasitis
compiled,evenbeforecompilinganythingelse.Theotherblocks,includingnormalcode,do
notexecuteuntilaftertheentireprogramhasbeencompiled.Whenanythingotherthana
BEGINblockisencountered,theyarecompiledandscheduledforexecution,butperl
continuescompilingtherestoftheprogram.TheexecutionorderisCHECK,INIT,normal
code,andENDblocks.CHECK>Scheduletheseblocksforexecutionafterallsourcecode
hasbeencompiled.INIT>ScheduletheseblocksforexecutionaftertheCHECKblockshave
executed.normalcode>SchedulenormalcodetoexecuteafterallINITblocks.END>
Scheduleforexecutionafternormalcodehascompleted.MultipleBEGINblocksareexecuted
immediatelyinNORMALdeclarationorder.MultipleCHECKblocksarescheduledtoexecute
inREVERSEdeclarationorder.MultipleINITblocksarescheduledtoexecuteinNORMAL
declarationorder.MultipleENDblocksarescheduledtoexecuteinREVERSEdeclaration
order.AnexamplecontainingseveralCHECK,INIT,normalcode,andENDblocks.The
outputshowstheexecutionorder:
END{print"END1\n"}
CHECK{print"CHECK1\n"}
BEGIN{print"BEGIN1\n"}

INIT{print"INIT1\n"}
print"normal\n"
INIT{print"INIT2\n"}
BEGIN{print"BEGIN2\n"}
CHECK{print"CHECK2\n"}
END{print"END2\n"}
>BEGIN1
>BEGIN2
>CHECK2
>CHECK1
>INIT1
>INIT2
>normal
>END2
>END1

7CodeReuse,PerlModules
Letssayyoucomeupwithsomereallygreatchunksofperlcodethatyouwanttousein
severaldifferentprograms.Perhapsyouhavesomesubroutinesthatareespeciallyhandy,
andperhapstheyhavesomeprivatedataassociatedwiththem.Thebestplacetoputcode
tobeusedinmanydifferentprogramsisina"PerlModule",andthen"use"thatmodule.A
perlmoduleisreallyjustafilewithaninventednameanda".pm"extension.The"pm"is
shortfor"perlmodule".Ifyouhadsomehandycodeformodelingadog,youmightputitina
modulecalledDog.pm,andthenyouwouldusethe"use"statementtoreadinthe
module.Thecontentofaperlmoduleisanyvalidperlcode.Generally,perlmodulescontain
declarations,suchassubroutinedeclarationsandpossiblydeclarationsofprivateorpublic
variables.Thesedeclaredsubroutinescanbecalledandpublicvariablescanbeaccessedby

anyperlscriptthatusesthemodule.Itisstandardconventionthatallperlmodulesstartout
witha"package"declarationthatdeclaresthepackagenamespacetobethesameasthe
modulename.Afteranynewpackagedeclarationyouwillneedtoturnonwarnings,etc.Here
isanexampleofourDogmodule.
###filename:Dog.pm
packageDog
usewarningsusestrictuseData::Dumper
subSpeak{print"Woof!\n"}
1#MUSTBELASTSTATEMENTINFILE

Allperlmodulesmustendwith"1"otherwiseyouwillgetacompileerror:
Dog.pmdidnotreturnatruevalue...

8TheuseStatement
The"use"statementallowsaperlscripttobringinaperlmoduleandusewhatever
declarationshavebeenmadeavailablebythemodule.Continuingourexample,afilecalled
script.plcouldbringintheDogmodulelikethis:
useDog
Dog::Speak
>Woof!

Bothfiles,Dog.pmandscript.pl,wouldhavetobeinthesamedirectory.TheDogmodule
declaresitspackagenamespacetobeDog.Themodulethendeclaresasubroutinecalled
"Speak",which,likeanynormalsubroutine,endsupinthecurrentpackagenamespace,Dog.
OncetheDogmodulehasbeenused,anyonecancallthesubroutinebycallingDog::Speak

9TheuseStatement,Formally
The"use"statementcanbeformallydefinedasthis:
useMODULENAME(LISTOFARGS)

The"use"statementisexactlyequivalenttothis:
BEGIN

{
requireMODULENAME
MODULENAME>import(LISTOFARGS)
}

TheMODULENAMEfollowsthepackagenamespaceconvention,meaningitwouldbeeither
asingleidentifierormultipleidentifiersseparatedbydoublecolons.Theseareallvalid
MODULENAMES:
useDog
usePets::Dog
usePets::Dog::GermanShepard
usePets::Cat::Persian

Usercreatedmodulenamesshouldbemixedcase.Modulenameswithalllowercaseare
reservedforbuiltinpragmas,suchas"usewarnings"Modulenameswithalluppercase
lettersarejustuglyandcouldgetconfusedwithbuiltinwords.The"require"statementis
whatactuallyreadsinthemodulefile.Whenperformingthesearchforthemodulefile,
"require"willtranslatethedoublecolonsintowhateverdirectoryseparatorisusedonyour
system.ForLinuxstylesystems,itwouldbea"/".Soperlwouldlookfor
Pets::Dog::GermanShepardinPets/Dog/forafilecalledGermanShepard.pm

9.1The@INCArray
The"require"statementwilllookforthemodulepath/fileinallthedirectorieslistedinaglobalarray
called@INC.Perlwillinitializethisarraytosomedefaultdirectoriestolookforanymodules.Ifyou
wanttocreateasubdirectoryjustforyourmodules,youcanaddthissubdirectoryto@INCandperl
willfindanymoduleslocatedthere.
Becausethe"require"statementisinaBEGINblock,though,itwillexecuteimmediatelyafter
beingcompiled.Sothiswillnotwork:
push(@INC,'/home/username/perlmodules')
useDogs

Thisisbecausethe"push"statementwillgetcompiledandthenbescheduledforexecution
aftertheentireprogramhasbeencompiled.The"use"statementwillgetcompiledand
executedimmediately,beforethe"push"isexecuted,so@INCwillnotbechangedwhen
"use"iscalled.Youcouldsaysomethinglikethis:
BEGIN{push(@INC,'/home/username/perlmodules')}
useDogs

9.2TheuselibStatement
The"uselib"statementismypreferredwayofaddingdirectorypathstothe@INCarray,
becauseitdoesnotneedaBEGINblock.Justsaysomethinglikethis:
uselib'/home/username/perlmodules'

Also,foryouLinuxheads,notethatthehomedirectorysymbol"~"isonlymeaningfulina
linuxshell.Perldoesnotunderstandit.Soifyouwanttoincludeadirectoryunderyourhome
directory,youwillneedtocall"glob"totranslate"~"tosomethingperlwillunderstand.The
"glob"functionusestheshelltranslationsonapath.
uselibglob('~/perlmodules')
useDogs

9.3ThePERL5LIBandPERLLIBEnvironmentVariables
The"require"statementalsosearchesforMODULENAMEinanydirectorieslistedinthe
environmentvariablecalledPERL5LIB.ThePERL5LIBvariableisacolonseparatedlistof
directorypaths.Consultyourshelldocumentationtodeterminehowtosetthisenvironment
variable.Ifyoudon'thavePERL5LIBset,perlwillsearchforMODULENAMEinanydirectory
listedinthePERLLIBenvironmentvariable.

9.4TherequireStatement
Oncetherequirestatementhasfoundthemodule,perlcompilesit.Becausetherequire
statementisinaBEGINblock,themodulegetsexecutedimmediatelyaswell.Thismeans
anyexecutablecodegetsexecuted.Anycodethatisnotadeclarationwillexecuteatthis
point.TheMODULENAME>importstatementisthenexecuted.

9.5MODULENAME>import(LISTOFARGS)
TheMODULENAME>import(LISTOFARGS)statementisa"methodcall",whichhasnot
beenintroducedyet.Amethodcallisafancywayofdoingasubroutinecallwithacoupleof
extrabellsandwhistlesboltedon.Basically,ifyourperlmoduledeclaresasubroutinecalled
"import"thenitwillgetexecutedatthistime.Moreadvancedly,oneofthebellsandwhistles
ofamethodcallisathingcalled"inheritance",whichhasnotbeenintroducedyet.So,tobe
moreaccurate,ifyourperlmoduleORITSBASECLASS(ES)declaresasubroutinecalled
"import"thenitwillgetexecutedatthistime.Theimportmethodisawayforamoduleto
importsubroutinesorvariablestothecaller'spackage.Thishappenswhenyouuse
Data::Dumperinyourscript.Whichiswhyyoucansay
useData::Dumper
printDumper\@var

insteadofhavingtosay:
useData::Dumper
printData::Dumper::Dumper\@var

Asubroutinecalled"Dumper"fromthepackageData::Dumpergetsimportedintoyour
packagenamespace.

9.6TheuseExecutionTimeline
Thefollowingexampleshowsthecompleteexecutiontimelineduringausestatement.
#!/usr/local/envperl
###filename:script.pl
usewarningsusestrictuseData::Dumper
warn"justbeforeuseDog"
useDog('GermanShepard')
warn"justafteruseDog"
Dog::Speak

###filename:Dog.pm
packageDog
usewarningsusestrictuseData::Dumper
warn"executingnormalcode"
subSpeak{print"Woof!\n"}
subimport{
warn"callingimport"
print"withthefollowingargs\n"
printDumper\@_
}
1#MUSTBELASTSTATEMENTINFILE
>executingnormalcodeatDog.pmline4.
>callingimportatDog.pmline7.
>withthefollowingargs
>$VAR1=[
>'Dog',
>'GermanShepard'
>]
>justbeforeuseDogat./script.plline4.
>justafteruseDogat./script.plline6.
>Woof!

10bless()
Thebless()functionissosimplethatpeopleusuallyhaveahardtimeunderstandingitbecausethey

makeitfarmorecomplicatedthanitreallyis.Allblessdoesischangethestringthatwouldbe
returnedwhenref()iscalled.Thebless()functionisthebasisforObjectOrientedPerl,butbless()by
itselfisoverwhelminglysimple.
Quickreferencerefresher:Givenanarrayreferent,@arr,andareference,$rarr=\@arr,then
callingref($rarr)willreturnthestring"ARRAY".
my@arr=(1,2,3)#referent
my$rarr=\@arr#referencetoreferent
my$str=ref($rarr)#callref()
warn"stris'$str'"
>stris'ARRAY'

Normally,ref()willreturnSCALAR,ARRAY,HASH,CODE,oremptystringdependingon
whattypeofreferentitisreferredto.
warnref(\4)
warnref([])
warnref({})
warnref(sub{})
warn"'".ref(4)."'"
>SCALARat./script.plline4.
>ARRAYat./script.plline5.
>HASHat./script.plline6.
>CODEat./script.plline7.
>''at./script.plline8.

Theblessfunctiontakesareferenceandastringasinput.Theblessfunctionmodifiesthe
referentpointedtobythereferenceandattachesthegivenstringsuchthatref()willreturn
thatstring.Theblessfunctionwillthenreturntheoriginalreference.
blessREFERENCE,STRING

Hereisanexampleofbless()inaction.Notethisisexactlythesameasthecodeinthefirst
example,butwithonelineaddedtodothebless:
my@arr=(1,2,3)#referent
my$rarr=\@arr#referencetoreferent
bless($rarr,"Counter")
my$str=ref($rarr)#callref()
warn"stris'$str'"
>stris'Counter'

Sincebless()returnsthereference,wecancallref()onthereturnvalueandaccomplishitin
oneline:
my$sca=4
warnref(bless(\$sca,"Four"))
warnref(bless([],"Box"))
warnref(bless({},"Curlies"))
warnref(bless(sub{},"Action"))
>Fourat./script.plline5.
>Boxat./script.plline6.
>Curliesat./script.plline7.
>Actionat./script.plline8.

Allbless()doesisaffectthevaluereturnedbyref().Thatisit.Youmightbewonderingwhy
theword"bless"waschosen.Ifareligiousfiguretookwaterandblessedit,thenpeople
wouldrefertoitas"holywater".Theconstitutionandmakeupofthewaterdidnotchange,
howeveritwasgivenanewname,andbecauseofthatnameitmightbeuseddifferently.In
perl,bless()changesthenameofareferent.Itdoesnotaffectthecontentsofthereferent,
onlythenamereturnedbyref().Butbecauseofthisnewname,thereferentmightbeused
differentlyorbehavedifferently.Wewillseethisdifferencewithmethodcalls.

11MethodCalls
Wehaveseenmethodcallsbefore.TheMODULENAME>import(LISTOFARGS)wasa
methodcall,butwehadtodosomehandwavingtogetbeyondit,callingitafancysubroutine
call.Quickreviewofpackagequalifiedsubroutinenames:Whenyoudeclareasubroutine,it
goesintothecurrentpackagenamespace.Youcancallthesubroutineusingitsshortnameif
youarestillinthepackage.Oryoucanusethefullyqualifiedpackagename,andbe
guaranteeditwillworkeverytime.
packageDog
subSpeak{print"Woof\n"}
Speak
Dog::Speak
>Woof
>Woof

Amethodcallissimilar.Hereisthegenericdefinition:
INVOCANT>METHOD(LISTOFARGS)

TheINVOCANTisthethingthat"invoked"theMETHOD.Aninvocantcanbeseveraldifferent
things,butthesimplestthingitcanbeisjustabarewordpackagenametogolookforthe
subroutinecalledMETHOD.
Dog>Speak
>Woof

SoitisalmostthesameasusingapackagequalifiedsubroutinenameDog::Speak.Sowhat
isdifferent?First,theINVOCANTalwaysgetsunshiftedintothe@_arrayinthesubroutine
call.
packageDog

usewarningsusestrictuseData::Dumper
subSpeak{
printDumper\@_

}
Dog>Speak(3)
>$VAR1=[
>'Dog',#INVOCANT
>3#firstuserargument
>]

Thismaynotseemveryuseful,butanINVOCANTcanbemanydifferentthings,somemore
usefulthanothers.Theseconddifferencebetweenasubroutinecallandamethodcallis
inheritance.

11.1Inheritance
Sayyouwanttomodelseveralspecificbreedsofdogs.Thespecificbreedsofdogswilllikely
beabletoinheritsomebehaviors(subroutine/methods)fromabaseclassthatdescribesall
dogs.SaywemodelaGermanShepardthathastheabilitytotrackascentbetterthanother
breeds.ButGermanShepardsstillbarklikealldogs.
###filename:Dog.pm
packageDog
usewarningsusestrictuseData::Dumper
subSpeak{
my($invocant,$count)=@_
warn"invocantis'$invocant'"
for(1..$count){warn"Woof"}
}
1
###filename:Shepard.pm
packageShepard

usebaseDog
subTrack{warn"sniff,sniff"}
1
#!/usr/local/envperl
###filename:script.pl
useShepard
Shepard>Speak(2)
Shepard>Track
>invocantis'Shepard'atDog.pmline6.
>WoofatDog.pmline8.
>WoofatDog.pmline8.
>sniff,sniffatShepard.pmline4.

Noticethatscript.plusedShepard,notDog.Andscript.plalwaysusedShepardasthe
invocantforitsmethodcalls.Whenscript.plcalledShepard>Speak,perlfirstlookedinthe
ShepardnamespaceforasubroutinecalledShepard::Speak.Itdidnotfindone.Sothenit
lookedandfoundaBASEofShepardcalledDog.Itthenlookedforasubroutinecalled
Dog::Speak,foundone,andcalledthatsubroutine.Alsonoticethatthesubroutine
Dog::Speakreceivedaninvocantof"Shepard".Eventhoughperlendedupcalling
Dog::Speak,perlstillpassesDog::Speaktheoriginalinvocant,whichwas"Shepard"inthis
case.ShepardINHERITEDtheSpeaksubroutinefromtheDogpackage.Theunexplainedbit
ofmagicisthatinheritanceusesthe"usebase"statementtodeterminewhatpackagesto
inheritfrom.

11.2usebase
Thisstatement:
usebaseMODULENAME

isfunctionallyidenticaltothis:

BEGIN
{
requireMODULENAME
push(@ISA,MODULENAME)
}

TherequirestatementgoesandlooksforMODULENAME.pmusingthesearchpatternthat
wedescribedinthe"use"sectionearlier.Thepush(@ISA,MODULENAME)isnew.Whena
methodcalllooksinapackagenamespaceforasubroutineanddoesnotfindone,itwillthen
gothroughthecontentsofthe@ISAarray.The@ISAarraycontainsanypackagesthatare
BASEpackagesofthecurrentpackage.The@ISAarrayisnamedthatwaybecause
"Shepard"ISA"Dog",thereforeISA.Thesearchorderisdepthfirst,lefttoright.Thisisnot
necessarilythe"best"waytosearch,butitishowperlsearches,soyouwillwanttolearnit.If
thisapproachdoesnotworkforyourapplication,youcanchangeitwithamodulefrom
CPAN.ImagineaChildmodulehasthefollowingfamilyinheritancetree:
Child.pm=>@ISA=qw(FatherMother)
Father.pm=>@ISA=qw(FathersFatherFathersMother)
Mother.pm=>@ISA=qw(MothersFatherMothersMother)
FathersFather.pm=>@ISA=()
FathersMother.pm=>@ISA=()
MothersFather.pm=>@ISA=()
MothersMother.pm=>@ISA=()

PerlwillsearchforChild>Methodthroughtheinheritancetreeinthefollowingorder:
Child
Father
FathersFather
FathersMother
Mother

MothersFather
MothersMother

11.3INVOCANT>isa(BASEPACKAGE)
The"isa"methodwilltellyouifBASEPACKAGEexistsanywhereinthe@ISAinheritance
tree.
Child>isa("MothersMother")#TRUE
Child>isa("Shepard")#FALSE

11.4INVOCANT>can(METHODNAME)
The"can"methodwilltellyouiftheINVOCANTcancallMETHODNAMEsuccessfully.
Shepard>can("Speak")#TRUE(Woof)
Child>can("Track")#FALSE(can'ttrackascent)

11.5InterestingInvocants
Sofarwehaveonlyusedbarewordinvocantsthatcorrespondtopackagenames.
Shepard>Track

Perlallowsamoreinterestinginvocanttobeusedwithmethodcalls:ablessedreferent.
Rememberbless()changesthestringreturnedbyref().Well,whenusingareferenceasan
invocant,perlwillcallref()onthereferenceandusethestringreturnedasstartingpackage
namespacetobeginsearchingforthemethod/subroutine.HereisoursimpleDogexample
butwithablessedinvocant.
###filename:Dog.pm
packageDog
usewarningsusestrictuseData::Dumper
subSpeak{
my($invocant,$count)=@_
warn"invocantis'$invocant'"

for(1..$count){warn"Woof"}
}1
#!/usr/local/envperl
###filename:script.pl
useDog
my$invocant=bless{},'Dog'###BLESSEDINVOCANT
$invocant>Speak(2)
>invocantis'Dog=HASH(0x8124394)'atDog.pmline6
>WoofatDog.pmline8.
>WoofatDog.pmline8.

Themy$invocant=bless{},"Dog"isthenewline.Theblesspartcreatesan
anonymoushash,{},andblessesitwiththename"Dog".Ifyoucalledref($invocant),itwould
returnthestring"Dog".Soperluses"Dog"asits"child"classtobeginitsmethodsearch
throughthehierarchytree.Whenitfindsthemethod,itpassestheoriginalinvocant,the
anonmoushash,tothemethodasthefirstargument.Well,sincewehaveananonymous
hashpassedaroundanyway,maybewecoulduseittostoresomeinformationaboutthe
differentdogsthatwearedealingwith.Infact,wealreadyknowallthegrammarweneedto
knowaboutObjectOrientedPerlProgramming,wejustneedtospeakdifferentsentences
now.

12ProceduralPerl
Sofar,alltheperlcodingwehavedonehasbeen"procedural"perl.Whenyouhear"procedural"think
of"Picard",asinCaptainPicardofthestarshipEnterprise.Picardalwaysgavetheship'scomputer
commandsintheformofproceduralstatements.
Computer,setwarpdriveto5.
Computer,setshieldsto"off".
Computer,fireweapons:phasersandphoton

torpedoes.

Thesubjectofthesentenceswasalways"Computer".Inproceduralprogramming,the
subject"computer"isimplied,thewaythesubject"you"isimpliedinthesentence:
"Stop!"TheverbanddirectobjectofPicard'ssentencesbecomethesubroutinenamein
proceeduralprogramming.Whateverisleftbecomeargumentspassedintothesubroutine
call.
set_warp(5)
set_shield(0)
fire_weaponsqw(phasersphoton_torpedoes)

13ObjectOrientedPerl
Objectorientedperldoesnotuseanimplied"Computer"asthesubjectforitssentences.
Instead,ituseswhatwasthedirectobjectintheproceduralsentencesandmakesitthe
subjectinobjectorientedprogramming.
WarpDrive,setyourselfto5.
Shields,setyourselfto"off".
Phasors,fireyourself.
Torpedoes,fireyourself.

Buthowwouldwecodethesesentences?Let'sstartwithafamiliarexample,ourDog
module.Assumewewanttokeeptrackofseveraldogsatonce.Perhapswearecodingup
aninventorysystemforapetstore.First,wewantacommonwaytohandleallpets,sowe
createanAnimal.pmperlmodule.Thismodulecontainsonesubroutinethattakesthe
invocantandaName,putstheNameintoahash,blessesthehash,andreturnsareference
tothehash.Thisreturnvaluebecomesa"Animal"object.Thissubroutineisanobject
contructor.ThenwecreateaDogmodulethatusesAnimalasitsbasetogetthecontructor.
Wethenaddamethodtoletdogsbark.Themethodprintsthenameofthedogwhenthey
barksoweknowwhosaidwhat.Thescript.plcreatesthreedogsandstorestheminanarray.
ThescriptthengoesthroughthearrayandcallstheSpeakmethodoneachobject.
###filename:Animal.pm
packageAnimal

subNew{
my($invocant,$name)=@_
returnbless({Name=>$name},$invocant)
}1
###filename:Dog.pm
packageDog
usebaseAnimal
subSpeak{
my($obj)=@_
my$name=$obj>{Name}
warn"$namesaysWoof"
}1
#!/usr/local/envperl
###filename:script.pl
useDog
my@pets
#create3Dogobjectsandputthemin@petsarray
foreachmy$nameqw(ButchSpikeFluffy){
push(@pets,Dog>New($name))
}
#haveeverypetspeakforthemselves.
foreachmy$pet(@pets){$pet>Speak}
>ButchsaysWoofatDog.pmline7.

>SpikesaysWoofatDog.pmline7.
>FluffysaysWoofatDog.pmline7.

Noticethelastforeachloopinscript.plsays$pet>Speak.Thisisobjectoriented
programming,becauseifyoutranslatedthatstatementtoEnglish,itwouldbe"Pet,speakfor
yourself".Thesubjectofthesentenceis"Pet",ratherthantheimplied"Computer"of
proceduralprogramming.ObjectOrientedProgrammingstatementsareoftheform:
$subject>verb(adjectives,adverbs,etc)

13.1Class
Theterm"class"isjustanObjectOrientedwayofsaying"packageandmodule".

13.2Polymorphism
Polymorphismisarealfancywayofsayinghavingdifferenttypesofobjectsthathavethe
samemethods.Expandingourpreviousexample,wemightwanttoaddaCatclasstohandle
catsatthepetstore.
###filename:Cat.pm
packageCat
usebaseAnimal
subSpeak{
my$obj=shift
my$name=$obj>{Name}
warn"$namesaysMeow"
}1

Thenwemodifyscript.pltoputsomecatsinthe@petsarray.
#!/usr/local/envperl
###filename:script.pl
useDoguseCat

my@pets
#createsomedogobjects
foreachmy$nameqw(ButchSpikeFluffy){
push(@pets,Dog>New($name))
}
#createsomecatobjects
foreachmy$nameqw(FangFurballFluffy){
push(@pets,Cat>New($name))
}
#haveallthepetssaysomething.
foreachmy$pet(@pets){
$pet>Speak#polymorphismatwork
}
>ButchsaysWoofatDog.pmline7.
>SpikesaysWoofatDog.pmline7.
>FluffysaysWoofatDog.pmline7.
>FangsaysMeowatCat.pmline7.
>FurballsaysMeowatCat.pmline7.
>FluffysaysMeowatCat.pmline7.

Noticehowthelastloopgoesthroughallthepetsandhaseachonespeakforthemselves.
Whetheritsadogorcat,theanimalwillsaywhateverisappropriateforitstype.Thisis
polymorphism.Thecodeprocessesabunchofobjectsandcallsthesamemethodoneach
object.Andeachobjectjustknowshowtodowhatitshoulddo.

13.3SUPER

SUPER::isaninterestingbitofmagicthatallowsachildobjectwithamethodcallthatsame
methodnameinitsparent'sclass.Backtothedogs.Toshortentheexample,theconstructor
NewwasmovedtoDog.pm.TheShepardmoduleusesDogasitsbase,andhasaSpeak
methodthatgrowls,andthencallsitsancestor'sDogversionofspeak.
###filename:Dog.pm
packageDog
subNew{
returnbless({Name=>$_[1]},$_[0])
}
subSpeak{
my$name=$_[0]>{Name}
warn"$namesaysWoof"
}1
###filename:Shepard.pm
packageShepard
usebaseDog
subSpeak{
my$name=$_[0]>{Name}
warn"$namesaysGrrr"
$_[0]>SUPER::Speak###SUPER
}1
#!/usr/local/envperl
###filename:script.pl
usewarningsusestrictuseData::Dumper
useShepard

my$dog=Shepard>New("Spike")
$dog>Speak
>SpikesaysGrrratShepard.pmline6.
>SpikesaysWoofatDog.pmline8.

WithoutthemagicofSUPER,theonlywaythatShepardcancallDog'sversionofspeakisto
useafullypackagequalifiednameDog::Speak()Butthisscattershardcodednamesofthe
baseclassthroughoutShepard,whichwouldmakechangingthebaseclassalotofwork.If
Shepard'sversionofSpeaksimplysaid$_[0]>Speak,itwouldgetintoaninfiniteloopcalling
itselfrecursively.SUPERisawayofsaying,"lookatmyancestorsandcalltheirversionof
thismethod."TherearesomelimitationswithSUPER.Considerthebigfamilytreeinheritance
diagraminthe"usebase"sectionofthisdocument(theonewithChildastheroot,Father
andMotherasparents,andFathersFather,FathersMother,etcasgrandparents).Imaginean
objectoftype"Child".If"Father"hasamethodcalledSpeakandthatmethodcalls
SUPER::Speak,theonlymodulesthatwillgetlookedatis"FathersFather"and
"FathersMother".SUPERlooksupthehierarchystartingattheclassfromwhereitwas
called.ThismeansifthemethodFathersFatherneededtocallwasinMothersMother,then
SUPERwillnotwork.Thiscouldbeconsideredagoodthing,sinceyouwouldassumethat
FatherwasdesignedonlyknowingaboutFathersFatherandFathersMother.WhenFather
wascoded,MothersMotherwasacompletestrangerhewouldnotmeetforyearstocome.
SodesigningFathertorelyonhisfuture,havenotevenmetheryetmotherinlaw,couldbe
consideredabadthing.However,itislegitimatetohavewhatyoumightconsidertobe
"universal"methodsthatexistforeveryclass.Insteadofaclasscalled"Child"imaginea
classcalled"CoupleAboutToGetMarried",andeverybaseclasshasamethodcalled
"ContributeToWedding".Inthatcase,everyclasscoulddoitspart,andthencall
SUPER::ContributeToWedding.TheFatherOfTheBridewouldpayforthewedding,the
FatherOfTheGroomwouldpayfortherehersaldinner,andsoonandsoforth.Unfortunately,
thereisnoeasy,builtinwaytodothisinperl.Iwillreferyoutothe"NEXT.pm"module
availableonCPAN.SUPERdoeshaveitsuses,though.Manytimesaclassmightexistthat
doesALMOSTwhatyouwantittodo.Ratherthanmodifytheoriginalcodetodowhatyou
wantitto,youcouldinsteadcreateaderivedclassthatinheritsthebaseclassandrewrite
themethodtodowhatyouwantittodo.Forexample,youmightwantamethodthatcallsits
parentmethodbutthenmultipliestheresultbyminusoneorsomething.Incaseslikethis,

SUPERwilldothetrick.

13.4ObjectDestruction
Objectdestructionoccurswhenallthereferencestoaspecificobjecthavegoneoutoflexical
scope,andtheobjectisscheduledforgarbagecollection.Justpriortodeletingtheobjectand
anyofitsinternaldata,perlwillcalltheDESTROYmethodontheobject.Ifnosuchmethod
exists,perlsilentlymovesonandcleansuptheobjectdata.
###filename:Dog.pm
packageDog
subNew{
returnbless({Name=>$_[1]},$_[0])
}
subDESTROY{
warn(($_[0]>{Name})."hasbeensold")
}1
#!/usr/local/envperl
###filename:script.pl
usewarningsusestrictuseData::Dumper
useDog
my$dog=Dog>New("Spike")
$dog=undef
>SpikehasbeensoldatDog.pmline7.

TheDESTROYmethodhassimilarlimitationsasSUPER.Withanobjectthathasacomplex
hierarchicalfamilytree,perlwillonlycalltheFIRSTmethodofDESTROYthatitfindsinthe
ancestry.IfMotherandFatherbothhaveaDESTROYmethod,thenMother'snotgoingto
handleherdemiseproperlyandyouwilllikelyhaveghostswhenyourunyourprogram.The

NEXT.pmmoduleonCPANalsosolvesthislimitation.

14ObjectOrientedReview
14.1Modules
Thebasisforcodereuseinperlisamodule.Aperlmoduleisafilethatendsin".pm"and
declaresapackagenamespacethat(hopefully)matchesthenameofthefile.Themodule
canbedesignedforproceduralprogrammingorobjectorientedprogramming(OO).Ifthe
moduleisOO,thenthemoduleissometimesreferredtoasa"class".

14.2useModule
Thecodeinaperlmodulecanbemadeavailabletoyourscriptbysaying"useMODULE"
The"use"statementwilllookforthemoduleinthedirectorieslistedinthePERL5LIB
environmentvariableandthenthedirectorieslistedinthe@INCvariable.Thebestwayto
adddirectoriestothe@INCvariableistosay
uselib"/path/to/dir"

Anydoublecolons(::)inthemodulenamebeingusedgetconvertedtoadirectoryseparator
symboloftheoperatingsystem.

14.3bless/constructors
Ifthemoduleisdesignedforproceduralprogramming,itwillprovidesubroutinedeclarations
thatcanbecalledlikenormalsubroutines.Ifthemoduleisdesignedforobjectorienteduse,it
willdeclaresubroutinesthatwillbeusedasconstructorsormethods.Constructorsare
subroutinesthatcreateareferencetosomevariable,usethereferencetoblessthevariable
intotheclass,andthenreturnthereference.Onceitsreferentisblessed,itcanbeusedas
anobject,andthereferenceisahandywayofpassingtheobjectaround.Theobjectis
usuallyahash.Keystothehashcorrespondtoobjectattributenames,andtheValues
correspondtotheattributevaluesspecifictothatparticularinstance.IntheAnimal.pm
moduleexample,onekeywas"Name",anddifferentinstanceshadNamevaluesof"Fluffy",
"Spike",andsoon.Thebestwayofcallingaconstructoristousethearrowoperator:
my$object=Classname>Constructor(arguments)

IntheAnimal.pmclass,thiswouldlooklike:
my$pet=Animal>New('Spike')

Thenameoftheconstructorcanbeanyvalidsubroutinename,butisusually"new"or
"New".

14.4Methods
Onceaninstanceofanobjecthasbeenconstructed,methodscanbecalledontheinstance
togetinformation,changevalues,performoperations,etc.Amethodissimplyasubroutine
thatreceivesareferencetotheinstancevariableasitsfirstargument.Methodsshouldbe
thoughtofas"actions"tobeperformedontheinstance,or"verbs"inasentenceswith
instancesbeingthe"subject".Intheaboveexamples,"Speak"wasamethodthatusedthe
Nameoftheinstancetoprintout"$namesayswoof".Thepreferredwayofcallingamethod
isusingthearrowmethod.
$ObjectInstance>Method(listofarguments)

IntheAnimal.pmexample,thiswouldlooklike:
$pet>Speak

14.5Inheritance
Classescaninheritmethodsfrombaseclasses.Thisallowsmanysimilarclassestoputall
theircommonmethodsinasinglebaseclass.Tohaveaclassinheritfromabaseclass,use
the"usebase"statement.
usebaseBaseClassName

Inoneexampleabove,theCatandDogclassesbothinheritfromacommonAnimalclass.
BothDogandCatclassesinherittheconstructor"New"methodfromtheAnimalbase
class.TheclassesCatandDoginheritfromthebaseclassAnimal.CatandDogare"derived"
fromAnimal.

14.6OverridingMethodsandSUPER
Classescanoverridethemethodsoftheirbaseclasses.Ifabaseclasscontainsamethod
called"MethodName",thenaderivedclasscanoverridethebaseclassmethodbydeclaring

itsownsubroutinecalledMethodName.Intheexamplesabove,theGermanShepardderived
classoverrodetheDogbaseclassSpeakmethodwithitsownmethod.
Ifaderivedclassoverridesamethodofitsbaseclass,itmaywanttocallitsbaseclassmethod.The
onlywaytoaccomplishthisiswiththeSUPER::pseudopackagename.TheGermanShepardmethod
namedSpeakcalledtheDogversionofSpeakbycalling:
$obj>SUPER::Speak

15CPAN
CPANisanacronymfor"ComprehensivePerlArchiveNetwork".ThereisaCPANwebsite,
whichcontainsaplethoraofperlmoduleforanyonetodownload.ThereisalsoaCPANperl
module,whichprovidesashellinterfaceforautomatingthedownloadingofperlmodules
fromtheCPANwebsite.A"perldoc"utilitycomeswithperlthatallowsviewingofPOD,which
is"PlainOldDocumentation"embeddedwithintheperlmodulesdownloadedfromCPAN.
Andfinally,thereisa"h2xs"utility,whichautomatesthecreationofamoduletobeuploaded
toCPAN.

15.1CPAN,TheWebSite
CPANisawebsitethatcontainsallthingsperl:help,FAQs,sourcecodetoinstallperl,and
mostimportantly,aplethoraofperlmodulesothatyoucanreusesomeoneelse'scode.
http://www.cpan.org

CPANcontainsanumberofsearchengines.Onceyoufindamodulethatmightdowhatyou
need,youcanviewtheREADMEfilethatisusuallyavailableonlinebeforeactually
downloadingthemodule.IftheREADMElookspromising,thendownloadthetarball,which
willbeafilewithatar.gzextension.Hereisthestandardinstallationstepsforamodule.This
exampleisfortheNEXT.pmmodule,whichiscontainedinNEXT0.60.tar.gz(youshoulduse
thelatestversion,ifavailable.)
>gunzipNEXT0.60.tar.gz
>tarxfNEXT0.60.tar
>cdNEXT0.60

Fromhere,mostmodulesinstallwiththeexactsamecommands:

>perlMakefile.PL
>make
>maketest
>suroot
>makeinstall
>exit

The"makeinstall"steprequiresrootprivileges.The"exit"stepisshownjustsoyou
remembertologoutfromroot.Ifyoudonothaverootprivilegesandthemoduleispureperl
(justa.pmfile),thenyoucancopythe.pmfiletoyourhomedirectory(oranywhereyouhave
read/writeprivileges),andthensetyourPERL5LIBenvironmentvariabletopointtothat
directory.

15.2CPAN,ThePerlModule
TheCPAN.pmmoduleisamodulethatautomatestheinstallationprocess.yougiveitthe
nameofamodule,anditdownloadsitfromtheweb,untarsit,andinstallsitforyou.More
interestingly,itwillinstallanydependenciesforyouaswell.Ifyouinstallamodulethat
requiresaseparatemodule,itinstallsbothmodulesforyouwithonecommand.CPAN.pmwill
wantyoutohavelynxinstalledonyourmachine.Lynxisatextbasedwebbrowser.CPAN.pm
willalsowantncftpget,whichisanInternetfiletransferprogramforscripts.Installtheseon
yoursystembeforerunningtheCPANmodule.TheCPAN.pmmoduleisrunfromashell
modeasroot(youneedrootprivilegestodotheinstall).Changetoroot,andthenrunthe
CPAN.pmmoduleshell.
>suroot
>perlMCPANeshell

Thefirsttimeitisrun,itwillaskyouabunchofconfigurationquestions.Mostcanbe
answeredwiththedefaultvalue(press<return>).HereisalogfromtheCPANbeingrunfor
thefirsttimeonmymachine:
Areyoureadyformanualconfiguration?[yes]
CPANbuildandcachedirectory?[/home/greg/.cpan]

Cachesizeforbuilddirectory(inMB)?[10]
Performcachescanning(atstartornever)?[atstart]
Cachemetadata(yes/no)?[yes]
YourterminalexpectsISO88591(yes/no)?[yes]
Policyonbuildingprerequisites(follow,askor
ignore)?[ask]
Whereisyourgzipprogram?[/usr/bin/gzip]
Whereisyourtarprogram?[/bin/tar]
Whereisyourunzipprogram?[/usr/bin/unzip]
Whereisyourmakeprogram?[/usr/bin/make]
Whereisyourlynxprogram?[]
>/usr/bin/lynx
Whereisyourwgetprogram?[/usr/bin/wget]
Whereisyourncftpgetprogram?[]
>/usr/bin/ncftpget
Whereisyourftpprogram?[/usr/bin/ftp]
Whatisyourfavoritepagerprogram?[/usr/bin/less]
Whatisyourfavoriteshell?[/bin/bash]
Parametersforthe'perlMakefile.PL'command?
Yourchoice:[]
Parametersforthe'make'command?
Yourchoice:[]
Parametersforthe'makeinstall'command?

Yourchoice:[]
TimeoutforinactivityduringMakefile.PL?[0]
Yourftp_proxy?
Yourhttp_proxy?
Yourno_proxy?
Selectyourcontinent(orseveralnearby
continents)[]
>5
Selectyourcountry(orseveralnearbycountries)[]
>3
SelectasmanyURLsasyoulike,
putthemononeline,separatedbyblanks[]
>3571113
EnteranotherURLorRETURNtoquit:[]
YourfavoriteWAITserver?
[wait://ls6www.informatik.unidortmund.de:1404]
cpan>

Thatlastlineisactuallythecpanshellprompt.Thenexttimeyouruncpan,itwillgodirectlytothe
cpanshellprompt.
Thefirstthingyouwillprobablywanttodoismakesureyouhavethelatestandgreatest
cpan.pmmodulewithallthetrimmings.Atthecpanshellprompt,typethefollowing
command:
cpan>installBundle::CPAN
cpan>reloadcpan

Youshouldthenbeabletoinstallanyperlmodulewithasinglecommand.Ifcpanencounters
anyproblems,itwillnotinstallthemodule.Ifyouwishtoforcetheinstall,thenusethe"force"
command.
cpan>forceinstallTk

Oryoucangetthetarballfromwww.cpan.organdinstallitmanually.

15.3PlainOldDocumentation(POD)andperldoc
ModulesonCPANaregenerallydocumentedwithPOD.PODembedsdocumentation
directlyintotheperlcode.YoudonotneedtoknowPODtowriteperlcode.Butyouwillwant
toknowhowtoreadPODfromallthemodulesyoudownloadfromCPAN.Perlcomeswitha
builtinutilitycalled"perldoc"whichallowsyoutolookupperldocumentationinPODformat.
>perldocperldoc
>perldocNEXT
>perldocData::Dumper

15.4CreatingModulesforCPANwithh2xs
IfyouwishtocreateamodulethatyouintendtouploadtoCPAN,perlcomeswithautility
"h2xs"which,amongotherthings,willcreateaminimalsetofallthefilesneeded.Thisfirst
commandwillcreateadirectorycalled"Animal"andpopulateitwithallthefilesyouneed.
Theremainderofthecommandsshowyouwhatstepsyouneedtotaketocreatea.tar.gz
tarballthatcanbeuploadedtoCPANanddownloadedbyothersusingthecpan.pmmodule.
>h2xsXnAnimal#createthestructure
>cdAnimal/lib#gointomoduledir
>editAnimal.pm#editmodule
>cd../t#gointotestdir
>editAnimal.t#edittest
>cd..#gotomakedirectory
>perlMakefile.PL#createmakefile

>make#runmake
>maketest#runthetestint/
>makedist#createa.tar.gzfile

16TheNextLevel
Younowknowthefundamentalsofproceduralperlandobjectorientedperl.Fromthispoint
forward,anynewtopicsmayincludeadiscussionofaperlbuiltinfeatureorsomething
availablefromCPAN.Someofperl'sbuiltinfeaturesaresomewhatlimitedandaCPAN
modulegreatlyenhancesand/orsimplifiesitsusage.

17CommandLineArguments
Scriptsareoftencontrolledbytheargumentspassedintoitviathecommandlinewhenthe
scriptisexecuted.Argumentsmightbeaswitch,suchas"h"togethelp.
>myscript.plh

A"v"switchmightturnverbosenesson.
>anotherscript.plv

Switchesmightbyfollowedbyanargumentassociatedwiththeswitch.A"in"switchmight
befollowedbyafilenametobeusedasinput.
>thatscript.plindata.txt

Anargumentcouldindicatetostopprocessingtheremainingargumentsandtoprocessthem
atalaterpointinthescript.The""argumentcouldbeusedtoindicatethatarguments
beforeitaretobeusedasperlargumentsandthatargumentsafteritaretobepassed
directlytoacompilerprogramthatthescriptwillcall.
>mytest.plintest42.txt+define+FAST

Moreadvancedarguments:Singlecharacterswitchescanbelumpedtogether.Insteadof"x
yz",youcouldsay"xyz".Optionscanbestoredinaseparatefile.Afilemightcontaina
numberofoptionsalwaysneededtodoastandardfunction,andusing"foptionfile.txt"would
beeasierthanputtingthoseoptionsonthecommandlineeachandeverytimethatfunction
isneeded.Thiswouldallowausertousetheoptionfileandthenaddotheroptionsonthe
commandline.

>thisscript.plfoptionfile.txtv

Optionscanhavefullandabbreviatedversionstoactivatethesameoption.Theoption"
verbose"canalsoworkas"v".Optionsoperateindependentofspacing.
f=options.txt
f=options.txt

17.1@ARGV
Perlprovidesaccesstoallthecommandlineargumentsviaaglobalarray@ARGV.Thetext
onthecommandlineisbrokenupanywherewhitespaceoccurs,exceptforquotedstrings.
#!/usr/bin/envperl
###filename:script.pl
usewarningsusestrictuseData::Dumper
printDumper\@ARGV
>script.plvfoptions.txt"helloworld"
>$VAR1=[
>'v',
>'f',
>'options.txt',
>'helloworld'
>]

Ifyouneedtopassinawildcardsuchas*.txtthenyouwillneedtoputitinquotesoryouroperating
systemwillreplaceitwithalistoffilesthatmatchthewildcardpattern.
#!/usr/bin/envperl
###filename:script.pl
usewarningsusestrictuseData::Dumper

printDumper\@ARGV
>./test.pl*.pl
>$VAR1=[
>'script.pl',
>'test.pl'
>]
>./test.pl"*.pl"
>$VAR1=[
>'*.pl'
>]

Simpleprocessingof@ARGVwouldshiftoffthebottomargument,processit,andmoveon
tothenextargument.Thefollowingexamplewillhandlesimplecommandlinearguments
describedabove.
#createapackagevariableforeachoption
our$fn
our$debug=0
#createsubroutinesforoptionsthatdothings
subprint_help{
print"dfordebug\nfforfilename\n"
}
#getthefirst/nextargumentandprocessit.
while(scalar(@ARGV)){
my$arg=shift(@ARGV)
if($argeq'h'){print_help}

elsif($argeq'f'){$fn=shift(@ARGV)}
elsif($argeq'd'){$debug=1}
else{die"unknownargument'$arg'"}
}

Package(our)variablesareusedinsteadoflexical(my)variablesbecausecommandlinearguments
shouldbeconsideredglobalandpackagevariablesareaccessibleeverywhere.Ifyouwroteascript
thatused"d"toturnondebuginformation,youwouldwantthistoturnondebugginginanyseparate
modulesthatyouwrite,notjustyourscript.plscript.
Package"main"isthedefaultpackageandagoodplacetoputcommandlineargument
relatedvariables.Outsideofpackagemain,codewouldcheckfor$main::debugbeingtrueor
false.Ifyouneedtohandleafewsimplecommandlineargumentsinyourscript,thenthe
aboveexampleofprocessing@ARGVoneatatimeisprobablysufficient.Ifyouneedto
supportmoreadvancedcommandlinearguments,oralotofsimpleones,youshouldlookat
Getopt::Declare.

17.2Getopt::Declare
TheGetopt::Declaremoduleallowsforaneasywaytodefinemorecomplicatedcommand
linearguments.Theaboveexamplewithh,f,anddoptionscouldbewrittenusing
Getopt::Declarelikethis:
useGetopt::Declare
our$fn=''
our$debug=0
my$args=Getopt::Declare>new(q(
in<filename>Defineinputfile
{$main::fn=$filename}
dTurndebuggingOn
{$main::debug=1}

<unknown>
{die"unknownarg'$unknown'\n"}
))
print"Debugis'$debug'\n"
print"fnis'$fn'\n"

ThetextpassedintoGetopt::Declareisamultilinequotedq()string.Thisstringdefinesthearguments
thatareacceptable.Noticethathisnotdefinedinthestring.ThisisbecauseGetopt::Declare
recognizeshtoprintouthelpbasedonthedeclaration.
>script.plh
>Options:
>in<filename>Defineinputfile
>dTurndebuggingOn

Theargumentdeclarationandtheargumentdescriptionisseparatedbyoneormoretabsin
thestringpassedintoGetopt::Declare.The<unknown>markerisusedtodefinewhataction
totakewithunknownarguments,argumentsthatarenotdefinedinthedeclaration.Thetext
withinthecurlybraces{$main::fn=$filename}istreatedasexecutablecodeandevaledifthe
declaredargumentisencounteredonthecommandline.Notethatwithinthecurlybraces,
theglobalvariables$fnand$debugareusedwiththeirfullpackagename.Also,notthatthe
startingcurlybracemustbeginonitsownlineseparatefromtheargumentdeclarationand
description.Getopt::Declarerecognizesvasaversioncommandlineargument.Ifvisonthe
commandline,itwillprintouttheversionofthefilebasedon$main::VERSION(ifitexists)
andthedatethefilewassaved.If[undocumented]iscontainedanywhereinthecommand
lineargumentdescription,thenthatargumentwillnotbelistedinthehelptext,butwillstillbe
recognizedifplacedonthecommandline(secretarguments)A[ditto]flaginthedescription
willusethesametextdescriptionastheargumentjustbeforeit,andanyactionassociated
withit.Ashortandlongversionofthesameargumentcanbelistedbyplacingtheoptional
secondhalfinsquarebrackets:verb[ose]Thiswillrecognizeverbandverboseasthe
sameargument.Normally,adeclaredargumentwillonlybeallowedtooccuronthecommand
lineonce.Iftheargumentcanoccurmorethanonce,place[repeatable]inthedescription.

Insidethecurlybraces,callingfinish()withatruevaluewillcausethecommandline
argumentstostopbeingprocessedatthatpoint.

17.2.1Getopt::DeclareSophisticatedExample
TheexampleonthenextpageshowsGetopt::Declarebeingusedmoretoitspotential.1.
Filenamestobehandledbythescriptcanbelistedonthecommandlinewithoutany
argumentprefix2.Verbositycanbeturnedonwithverbose.Itcanbeturnedoffwithquiet.3.
AnundocumentedDumpoptionturnsondumping.4.Anyoptionsafteradoubledash()are
leftin@ARGVforlaterprocessing.5.Additionalargumentscanbeplacedinanexternalfile
andloadedwithargsfilename.TheError()subroutinewillreportthenameofthefile
containinganyerrorwhileprocessingthearguments.Argumentfilescanrefertoother
argumentfiles,allowingnestedargumentfiles.6.Anyargumentsthatarenotdefinedwill
generateanerror.#advancedcommandlineargumentprocessinguseGetopt::Declareour
$arg_file='CommandLine'our$VERSION=1.01#vwillusethisour@filesour
$debug=0our$verbose=0our$dump=0subVerbose{if($verbose){print$_[0]}}sub
Error{die"Error:".($_[0])."from'$arg_file'\n"}my$grammar=q(
args<input>Argfile[repeatable]
{unless(e$input)
{main::Error("nofile'$input'")}
main::Verbose("Parsing'$input'\n")
{local($main::arg_file)
$main::arg_file=$input
$main::myparser>parse([$input])
}
main::Verbose("finishedparsing'$input'\n")
main::Verbose("returningto'$main::arg_file'\n")
}
dTurndebuggingOn
{$main::debug=1}

verb[ose]TurnverboseOn
{$main::verbose=1}
quietTurnverboseOff
{$main::verbose=0}
Dump[undocumented]Dumpon
{$main::dump=1}
hPrintHelp
{$main::myparser>usage}
Argumentseparator
{finish(1)}
<unknown>Filename[repeatable]
{if($unknown!~m{^[+]})
{push(@main::files,$unknown)}
else
{main::Error("unknownarg'$unknown'")}
}
)our$myparser=newGetopt::Declare($grammar,['BUILD'])$myparser>parse()

18FileInputandOutput
Perlhasanumberoffunctionsusedforreadingfromandwritingtofiles.AllfileIOrevolves
aroundfilehandles.

18.1open
Togenerateafilehandleandattachittoaspecificfile,usetheopen()function.
open(my$filehandle,'filename.txt')

ordie"Couldnotopenfile"

Ifthefirstargumenttoopen()isanundefinedscalar,perlwillcreateafilehandleandassignit
tothatscalar.Thisisavailableinperlversion5.6andlaterandisthepreferredmethodfor
dealingwithfilehandles.
Thesecondargumenttoopen()isthenameofthefileandanoptionalflagthatindicatestoopenthe
fileasread,write,orappend.Thefilenameisasimplestring,andtheflag,ifpresent,isthefirst
characterofthestring.Thevalidflagsaredefinedasfollows:
'<'Read.Donotcreate.
Donotclobberexistingfile.DEFAULT.
'>'Write.Createifnonexisting.
Clobberifalreadyexists.
'>>'Append.Createifnonexisting.
Donotclobberexistingfile.

Ifnoflagisspecified,thefiledefaultstobeingopenedforread.

18.2close
Onceopen,youcancloseafilehandlebycallingtheclosefunctionandpassingitthe
filehandle.
close($filehandle)ordie"Couldnotclose"

Ifthefilehandleisstoredinascalar,andthescalargoesoutofscopeorisassignedundef,
thenperlwillautomaticallyclosethefilehandleforyou.

18.3read
Onceopen,youcanreadfromafilehandleanumberofways.Themostcommonistoread
thefilehandlealineatatimeusingthe"angle"operator.Theangleoperatoristhefilehandle
surroundedbyanglebrackets.i.e.<$filehandle>Whenusedasthebooleanconditional
controllingawhile()loop,theloopreadsthefilehandlealineatatimeuntiltheendoffileis
reached.Eachpassthroughtheconditionaltestreadsthenextlinefromthefileandplacesit

inthe$_variable.Thisscriptshowsacatnstylefunction.
open(my$fh,'input.txt')ordie"couldnotopen"
my$num=0
while(<$fh>){
$num++
my$line=$_
chomp($line)
print"$num:$line\n"
}

Theaboveexampleisusefulifeverylineofthefilecontainsthesamekindofinformation,
andyouarejustgoingthrougheachlineandparsingit.Anotherwaytoreadfromafilehandle
istoassigntheangleoperatorofthefilehandletoascalar.Thiswillreadthenextlinefrom
thefilehandle.Butitrequiresthatyoutestthereturnvaluetomakesureitisdefined,
otherwiseyouhittheendoffile.
defined(my$line=<$fh>)ordie"prematureeof"

Tomakealittlemoreuseful,youcanwrapitupinasubroutinetohidetheerrorchecking.
Youcanthencallthesubroutineeachtimeyouwantaline.Thisisusefulifyouarereadinga
filewhereeverylinehasadifferentmeaning,andyouneedtoreaditinacertainorder.
useCarp
open(my$fh,'input.txt')
subnlin{
defined(my$line=<$fh>)orcroak"prematureeof"
chomp($line)
return$line
}
my$name=nlin

my$addr=nlin
my$age=nlin
print"Name:$name,address:$addr,age:$age\n"

18.4write
Ifthefileisopenedforwriteorappend,youcanwritetothefilehandleusingtheprint
function.
open(my$fh,'>output.txt')
print$fh"once\n"
print$fh"upon\n"
print$fh"atime\n"
close$fh

18.5FileTests
Perlcanperformtestsonafiletogleaninformationaboutthefile.Alltestsreturnatrue(1)or
false("")valueaboutthefile.Allthetestshavethefollowingsyntax:
xFILE

The"x"isasinglecharacterindicatingthetesttoperform.FILEisafilename(string)or
filehandle.Somecommontestsinclude:
efileexists
ffileisaplainfile
dfileisadirectory
lfileisasymboliclink
rfileisreadable
wfileiswritable
zfilesizeiszero

pfileisanamedpipe
Sfileisasocket
Tfileisatextfile(perl'sdefinition)

18.6FileGlobbing
Theglob()functiontakesastringexpressionandreturnsalistoffilesthatmatchthat
expressionusingshellstylefilenameexpansionandtranslation.
my@files=glob(STRING_EXPRESSION)

Forexample,ifyouwishtogetalistofallthefilesthatendwitha.txtexpression:
my@textfiles=glob("*.txt")

ThisisalsousefultotranslateLinuxstyle"~"homedirectoriestoausablefilepath.The"~"in
Linuxisashellfeaturethatistranslatedtotheuser'srealdirectorypathunderthehood.
Perl'sopen()functioncannotopen"~/list.txt"because"~"onlymeanssomethingtotheshell.
Totranslatetoarealdirectorypath,useglob().
my$startup_file=glob('~/.cshrc')

18.7FileTreeSearching
Forsophisticatedsearching,includingsearchesdownanentiredirectorystructure,usethe
File::Findmodule.Itisincludedinperl5.6.1.
useFile::Find
my$pwd=`pwd`
chomp($pwd)
find(\&process,$pwd)
subprocess{...}

Theprocess()subroutineisasubroutinethatyoudefine.Theprocess()subroutinewillbe
calledoneveryfileanddirectoryin$pwdandrecursivelyintoeverysubdirectoryandfile
below.Thepackagevariable$File::Find::namecontainsthenameofthecurrentfileor
directory.Yourprocess()subroutinecanreadthisvariableandperformwhatevertestingit

wantsonthefullname.Ifyouprocess()wascalledonafileandnotjustadirectory,thepath
tothefileisavailablein$File::Find::dirandthenameofthefileisin$_.Ifyour
process()subroutinesetsthepackagevariable$File::Find::pruneto1,thenfind()will
notrecurseanyfurtherintothecurrentdirectory.
Thisprocess()subroutineprintsoutall.txtfilesencounteredanditavoidsenteringanyCVS
directories.
subprocess{
my$fullname=$File::Find::name
if($fullname=~m{\.txt$})
{print"foundtextfile$fullname\n"}
if((d$fullname)and($fullname=~m{CVS}))
{$File::Find::prune=1return}
}

Formoreinformation:perldocFile::Find

19OperatingSystemCommands
Twowaystoissueoperatingsystemcommandswithinyourperlscriptarethesystem
functionandthebacktickoperator.
1.system("commandstring")
2.`commandstring`

19.1Thesystem()function
Ifyouwanttoexecutesomecommandandyoudonotcarewhattheoutputlookslike,you
justwanttoknowifitworked,thenyouwilllikelywanttousethesystem()function.The
system()functionexecutesthecommandstringinashellandreturnsyouthereturncodeof
thecommand.InLinux,areturnvalueofZEROisusuallygood,anonzeroindicatessome
sortoferror.Sotousethesystem()functionandcheckthereturnvalue,youmightdo
somethinglikethis:

my$cmd="rmfjunk.txt"
system($cmd)==0ordie"Error:couldnot'$cmd'"

Whenyouexecuteacommandviathesystem()function,theoutputofthecommandgoesto
STDOUT,whichmeanstheuserwillseetheoutputscrollbyonthescreen,andthenitislost
forever.

19.2TheBacktickOperator
IfyouwanttocapturetheSTDOUTofaoperatingsystemcommand,thenyouwillwantto
usethebacktickoperator.Asimpleexampleisthe"finger"commandonLinux.Ifyoutype:
linux>fingerusername

LinuxwilldumpabunchoftexttoSTDOUT.Ifyoucallsystem()onthefingercommand,all
thistextwillgotoSTDOUTandwillbeseenbytheuserwhentheyexecuteyourscript.Ifyou
wanttocapturewhatgoestoSTDOUTandmanipulateitwithinyourscript,usethebacktick
operator.
my$string_results=`fingerusername`

The$string_resultsvariablewillcontainallthetextthatwouldhavegonetoSTDOUT.You
canthenprocessthisinyourperlscriptlikeanyotherstring.

19.3OperatingSystemCommandsinaGUI
IfyourperlscriptisgeneratingaGUIusingtheTkpackage,thereisathirdwaytorunsystem
commandswithinyourperlscript,usingtheTk::ExecuteCommandmodule.Thisisavery
coolmodulethatallowsyoutorunsystemcommandsinthebackgroundasaseparate
processfromyoumainperlscript.Themoduleprovidestheuserwitha"Go/Cancel"button
andallowstheusertocancelthecommandinthemiddleofexecutionifitistakingtoo
long.WehavenotcoveredtheGUItoolkitforperl(Tk),butifyouaredoingsystem
commandsinperlandyouareusingTk,youshouldlookintoTk::ExecuteCommand.

20RegularExpressions
Regularexpressionsarethetextprocessingworkhorseofperl.Withregularexpressions,you
cansearchstringsforpatterns,findoutwhatmatchedthepatterns,andsubstitutethe

matchedpatternswithnewstrings.Therearethreedifferentregularexpressionoperatorsin
perl:
1.matchm{PATTERN}
2.substitutes{OLDPATTERN}{NEWPATTERN}
3.transliteratetr{OLD_CHAR_SET}{NEW_CHAR_SET}

Perlallowsanydelimiterintheseoperators,suchas{}or()or//or##orjustaboutany
characteryouwishtouse.Themostcommondelimiterusedisprobablythem//ands///
delimiters,butIprefertousem{}ands{}{}becausetheyareclearerforme.Therearetwo
waysto"bind"theseoperatorstoastringexpression:
1.=~patterndoesmatchstringexpression
2.!~patterndoesNOTmatchstringexpression

Bindingcanbethoughtofas"ObjectOrientedProgramming"forregularexpressions.
GenericOOPstructurecanberepresentedas
$subject>verb(adjectives,adverbs,etc)

BindinginRegularExpressionscanbelookedatinasimilarfashion:
$string=~verb(pattern)

where"verb"islimitedto'm'formatch,'s'forsubstitution,and'tr'fortranslate.Youmaysee
perlcodethatsimplylookslikethis:
/patt/

Thisisfunctionallyequivalenttothis:
$_=~m/patt/

Herearesomeexamples:
#spamfilter
my$email="ThisisagreatFreeOffer\n"
if($email=~m{FreeOffer})
{$email="*deletedspam*\n"}
print"$email\n"

#upgrademycar
my$car="mycarisatoyota\n"
$car=~s{toyota}{jaguar}
print"$car\n"
#simpleencryption,Caesarcypher
my$love_letter="HowIlovethee.\n"
$love_letter=~tr{AZaz}{NZAMnzam}
print"encrypted:$love_letter"
$love_letter=~tr{AZaz}{NZAMnzam}
print"decrypted:$love_letter\n"
>*deletedspam*
>mycarisajaguar
>encrypted:UbjVybirgurr.
>decrypted:HowIlovethee.

Theaboveexamplesalllookforfixedpatternswithinthestring.Regularexpressionsalso
allowyoutolookforpatternswithdifferenttypesof"wildcards".

20.1VariableInterpolation
Thebracesthatsurroundthepatternactasdoublequotemarks,subjectingthepatternto
onepassofvariableinterpolationasifthepatternwerecontainedindoublequotes.This
allowsthepatterntobecontainedwithinvariablesandinterpolatedduringtheregular
expression.
my$actual="Toyota"
my$wanted="Jaguar"
my$car="MycarisaToyota\n"

$car=~s{$actual}{$wanted}
print$car
>MycarisaJaguar

20.2WildcardExample
Intheexamplebelow,weprocessanarrayoflines,eachcontainingthepattern{filename:}followed
byoneormorenonwhitespacecharactersformingtheactualfilename.Eachlinealsocontainsthe
pattern{size:}followedbyoneormoredigitsthatindicatetheactualsizeofthatfile.
my@lines=split"\n",<<"MARKER"
filename:output.txtsize:1024
filename:input.datsize:512
filename:address.dbsize:1048576
MARKER

foreachmy$line(@lines){
####################################
#\Sisawildcardmeaning
#"anythingthatisnotwhitespace".
#the"+"means"oneormore"
####################################
if($line=~m{filename:(\S+)}){
my$name=$1
###########################
#\disawildcardmeaning
#"anydigit,09".

###########################
$line=~m{size:(\d+)}
my$size=$1
print"$name,$size\n"
}
}
>output.txt,1024
>input.dat,512
>address.db,1048576

20.3DefiningaPattern
Apatterncanbealiteralpatternsuchas{FreeOffer}.Itcancontainwildcardssuchas
{\d}.Itcanalsocontainmetacharacterssuchastheparenthesis.Noticeintheabove
example,theparenthesiswereinthepatternbutdidnotoccurinthestring,yetthepattern
matched.

20.4Metacharacters
Metacharactersdonotgetinterpretedasliteralcharacters.Insteadtheytellperltointerpretthe
metacharacter(andsometimesthecharactersaroundmetacharacter)inadifferentway.Thefollowing
aremetacharactersinperlregularexpressionpatterns:
\|()[]{}^$*+?.
\

(backslash)ifnextcharactercombinedwiththisbackslashformsacharacterclass
shortcut,thenmatchthatcharacterclass.Ifnotashortcut,thensimplytreatnext
characterasanonmetacharacter.

alternation:(patt1|patt2)means(patt1ORpatt2)

()
(?:)
.
[]

grouping(clustering)andcapturing

grouping(clustering)only.nocapturing.(somewhatfaster)

matchanysinglecharacter(usuallynot"\n")

defineacharacterclass,matchanysinglecharacterinclass

(quantifier):matchpreviousitemzeroormoretimes

(quantifier):matchpreviousitemoneormoretimes

(quantifier):matchpreviousitemzerooronetime

{}

(quantifier):matchpreviousitemanumberoftimesingivenrange

(positionmarker):beginningofstring(orpossiblyafter"\n")

(positionmarker):endofstring(orpossiblybefore"\n")

Examplesbelow.Changethevalueassignedto$strandrerunthescript.Experimentwith
whatmatchesandwhatdoesnotmatchthedifferentregularexpressionpatterns.my$str=
"Dearsir,helloandgoodday!"."dogsandcatsandsssnakesputmetosleep."."zzzz.Hummingbirdsareffffast.
"."Sincerely,John"#|alternation#match"hello"or"goodbye"if($str=~m{hello|goodbye}){warn"alt"}#()grouping
andcapturing#match'goodday'or'goodbye'if($str=~m{(good(day|bye))}){warn"groupmatched,captured'$1'"}#.
anysinglecharacter#match'cat''cbt''cct''c%t''c+t''c?t'...if($str=~m{c.t}){warn"period"}#[]defineacharacter
class:'a'or'o'or'u'#match'cat''cot''cut'if($str=~m{c[aou]t}){warn"class"}#*quantifier,matchpreviousitem
zeroormore#match''or'z'or'zz'or'zzz'or'zzzzzzzz'if($str=~m{z*}){warn"asterisk"}#+quantifier,match
previousitemoneormore#match'snake''ssnake''sssssssnake'if($str=~m{s+nake}){warn"plussign"}#?
quantifier,previousitemisoptional#matchonly'dog'and'dogs'if($str=~m{dogs?}){warn"question"}#{}
quantifier,matchprevious,3<=qty<=5#matchonly'fffast','ffffast',and'fffffast'if($str=~m{f{3,5}ast}){warn
"curlybrace"}#^positionmarker,matchesbeginningofstring#match'Dear'onlyifitoccursatstartof
stringif($str=~m{^Dear}){warn"caret"}#$positionmarker,matchesendofstring#match'John'onlyifitoccurs

atendofstringif($str=~m{John$}){warn"dollar"}>altat...>groupmatched,captured'goodday'at...>periodat
...>classat...>asteriskat...>plussignat...>questionat...>curlybraceat...>caretat...>dollarat...

20.5CapturingandClusteringParenthesis
Normalparentheseswillbothclusterandcapturethepatterntheycontain.Clusteringaffects
theorderofevaluationsimilartothewayparenthesesaffecttheorderofevaluationwithina
mathematicalexpression.Normally,multiplicationhasahigherprecedencethanaddition.
Theexpression"2+3*4"doesthemultiplicationfirstandthentheaddition,yieldingthe
resultof"14".Theexpression"(2+3)*4"forcestheadditiontooccurfirst,yieldingtheresult
of"20".Clusteringparenthesesworkinthesamefashion.Thepattern{cats?}willapplythe
"?"quantifiertotheletter"s",matchingeither"cat"or"cats".Thepattern{(cats)?}willapply
the"?"quantifiertotheentirepatternwithintheparentheses,matching"cats"ornullstring.

20.5.1$1,$2,$3,etcCapturingparentheses
ClusteringparentheseswillalsoCapturethepartofthestringthatmatchedthepatternwithin
parentheses.Thecapturedvaluesareaccessiblethroughsome"magical"variablescalled
$1,$2,$3,...Eachleftparenthesisincrementsthenumberusedtoaccessthecaptured
string.Theleftparenthesisarecountedfromlefttorightastheyoccurwithinthepattern,
startingat1.
my$test="Firstname:JohnLastname:Smith"
############################################
#$1$2
$test=~m{Firstname:(\w+)Lastname:(\w+)}
my$first=$1
my$last=$2
print"Hello,$first$last\n"
>Hello,JohnSmith

Becausecapturingtakesalittleextratimetostorethecapturedresultintothe$1,$2,
variables,sometimesyoujustwanttoclusterwithouttheoverheadofcapturing.Inthebelow
example,wewanttocluster"day|bye"sothatthealternationsymbol"|"willgowith"day"or

"bye".Withouttheclusteringparenthesis,thepatternwouldmatch"goodday"or"bye",rather
than"goodday"or"goodbye".Thepatterncontainscapturingparensaroundtheentire
pattern,sowedonotneedtocapturethe"day|bye"partofthepattern,thereforeweuse
clusteronlyparentheses.
if($str=~m{(good(?:day|bye))})
{warn"groupmatched,captured'$1'"}

Clusteronlyparenthesisdon'tcapturetheenclosedpattern,andtheydon'tcountwhen
determiningwhichmagicvariable,$1,$2,$3...,willcontainthevaluesfromthecapturing
parentheses.
my$test='gooddayJohn'
##########################################
#$1$2
if($test=~m{(good(?:day|bye))(\w+)})
{print"Yousaid$1to$2\n"}
>YousaidgooddaytoJohn

20.5.2Capturingparenthesesnotcapturing
Ifaregularexpressioncontainingcapturingparenthesesdoesnotmatchthestring,themagic
variables$1,$2,$3,etcwillretainwhateverPREVIOUSvaluetheyhadfromanyPREVIOUS
regularexpression.ThismeansthatyouMUSTchecktomakesuretheregularexpression
matchesBEFOREyouusethe$1,$2,$3,etcvariables.Intheexamplebelow,thesecond
regularexpressiondoesnotmatch,therefore$1retainsitsoldvalueof'be'.Insteadof
printingoutsomethinglike"NameisHoratio"or"Nameis"andfailingonanundefinedvalue,
perlinsteadkeepstheoldvaluefor$1andprints"Nameis'be'",instead.
my$string1='Tobe,ornottobe'
$string1=~m{notto(\w+)}#matches,$1='be'
warn"Thequestionisto$1"
my$string2='thatisthequestion'
$string2=~m{Iknewhimonce,(\w+)}#nomatch

warn"Nameis'$1'"
#nomatch,so$1retainsitsoldvalue'be'
>Thequestionistobeat./script.plline7.
>Nameis'be'at./script.plline11.

20.6CharacterClasses
The"."metacharacterwillmatchanysinglecharacter.Thisisequivalenttoacharacterclass
thatincludeseverypossiblecharacter.Youcaneasilydefinesmallercharacterclassesof
yourownusingthesquarebrackets[].Whatevercharactersarelistedwithinthesquare
bracketsarepartofthatcharacterclass.Perlwillthenmatchanyonecharacterwithinthat
class.
[aeiouAEIOU]anyvowel
[0123456789]anydigit

20.6.1MetacharactersWithinCharacterClasses
Withinthesquarebracketsusedtodefineacharacterclass,allpreviouslydefined
metacharactersceasetoactasmetacharactersandareinterpretedassimpleliteral
characters.Charactersclasseshavetheirownspecialmetacharacters.
\

(backslash)demetathenextcharacter

(hyphen)Indicatesaconsecutivecharacterrange,inclusively.
[af]indicatesthelettersa,b,c,d,e,f.
CharacterrangesarebasedoffofASCIInumericvalues.

Ifitisthefirstcharacteroftheclass,thenthisindicatesthe
class
isanycharacterEXCEPTtheonesinthesquarebrackets.
Warning:[^aeiou]meansanythingbutalowercasevowel.

This
isnotthesameas"anyconsonant".Theclass[^aeiou]will
matchpunctuation,numbers,andunicodecharacters.

20.7ShortcutCharacterClasses
Perlhasshortcutcharacterclassesforsomemorecommonclasses.
shortcut

class

description

\d

[09]

anydigit

\D

[^09]

anyNONdigit

\s

[\t\n\r\f]

anywhitespace

\S

[^\t\n\r\f]

anyNONwhitespace

\w

[azAZ09_]

anywordcharacter(validperlidentifier)

\W

[^azAZ09_]

anyNONwordcharacter

20.8Greedy(Maximal)Quantifiers
Quantifiersareusedwithinregularexpressionstoindicatehowmanytimesthepreviousitem
occurswithinthepattern.Bydefault,quantifiersare"greedy"or"maximal",meaningthatthey
willmatchasmanycharactersaspossibleandstillbetrue.
*

matchzeroormoretimes(matchasmuchaspossible)

matchoneormoretimes(matchasmuchaspossible)

matchzerooronetimes(matchasmuchaspossible)

{count}

matchexactly"count"times

{min,}

matchatleast"min"times(matchasmuchaspossible)

{min,max} matchatleast"min"andatmost"max"times
(matchasmuchaspossible)

20.9Thrifty(Minimal)Quantifiers
Placinga"?"afteraquantifierdisablesgreediness,makingthem"nongreedy","thrifty",or
"minimal"quantifiers.Minimalquantifiersmatchasfewcharactersaspossibleandstillbe
true.
*?

matchzeroormoretimes
(matchaslittleaspossibleandstillbetrue)

+?

matchoneormoretimes
(matchaslittleaspossibleandstillbetrue)

{min,}?

matchatleastmintimes
(matchaslittleaspossibleandstillbetrue)

{min,max}?

matchatleast"min"andatmost"max"times
(matchaslittleaspossibleandstillbetrue)

Thisexampleshowsthedifferencebetweenminimalandmaximalquantifiers.
my$string="12340000"

if($string=~m{^(\d+)0+$})
{print"greedy'$1'\n"}
if($string=~m{^(\d+?)0+$})
{print"thrifty'$1'\n"}
>greedy'1234000'
>thrifty'1234'

20.10PositionAssertions/PositionAnchors
Insidearegularexpressionpattern,somesymbolsdonottranslateintoacharacteror
characterclass.Instead,theytranslateintoa"position"withinthestring.Ifapositionanchor
occurswithinapattern,thepatternbeforeandafterthatanchormustoccurwithinacertain
positionwithinthestring.
^

Matchesthebeginningofthestring.
Ifthe/m(multiline)modifierispresent,matches"\n"also.

Matchestheendofthestring.
Ifthe/m(multiline)modifierispresent,matches"\n"also.

\A

Matchthebeginningofstringonly.Notaffectedby/mmodifier.

\z

Matchtheendofstringonly.Notaffectedby/mmodifier.

\Z

Matchestheendofthestringonly,butwillchomp()a"\n"ifthat
wasthelastcharacterinstring.

\b

word"b"oundary
Awordboundaryoccursinfourplaces.

1)atatransitionfroma\wcharactertoa\Wcharacter
2)atatransitionfroma\Wcharactertoa\wcharacter
3)atthebeginningofthestring
4)attheendofthestring

\B

NOT\b

\G

usuallyusedwith/gmodifier(probablywant/cmodifiertoo).
Indicatesthepositionafterthecharacterofthelastpatternmatch
performedonthestring.Ifthisisthefirstregularexpressionbegin
performedonthestringthen\Gwillmatchthebeginningofthe
string.Usethepos()functiontogetandsetthecurrent\Gposition
withinthestring.

20.10.1The\bAnchor
Usethe\banchorwhenyouwanttomatchawholewordpatternbutnotpartofaword.This
examplematches"jump"butnot"jumprope":
my$test1='Hecanjumpveryhigh.'
if($test1=~m{\bjump\b})
{print"test1matches\n"}
my$test2='Pickupthatjumprope.'
unless($test2=~m{\bjump\b})
{print"test2doesnotmatch\n"}
>test1matches
>test2doesnotmatch

20.10.2The\GAnchor
The\Ganchorisasophisticatedanchorusedtoperformaprogressionofmanyregular
expressionpatternmatchesonthesamestring.The\Ganchorrepresentsthepositionwithin
thestringwherethepreviousregularexpressionfinished.Thefirsttimearegularexpression
isperformedonastring,the\Ganchorrepresentsthebeginningofthestring.Thelocationof
the\Ganchorwithinastringcanbedeterminedbycallingthepos()functiononthestring.
Thepos()functionwillreturnthecharacterindexinthestring(indexzeroistotheleftofthe
firstcharacterinthestring)representingthelocationofthe\Ganchor.Assigningtopos($str)
willchangethepositionofthe\Ganchorforthatstring.The\Ganchorisusuallyusedwiththe
"cg"modifiers.The"cg"modifierstellperltoNOTresetthe\Ganchortozeroiftheregular
expressionfailstomatch.Thiswillallowaseriesofregularexpressionstooperateona
string,usingthe\Ganchortoindicatethelocationwherethepreviousregularexpression
finished.Withoutthe"cg"modifiers,thefirstregularexpressionthatfailstomatchwillreset
the\Ganchorbacktozero.Theexamplebelowusesthe\Ganchortoextractbitsof
informationfromasinglestring.Aftereveryregularexpression,thescriptprintsthepos()
valueofthestring.Noticehowthepos()valuekeepsincreasing.
my$str="Firstname:JohnLastname:Smith
Bookcollection:ProgrammingPerl,PerlCookbook,
ImpatientPerl"
if($str=~m{\GFirstname:(\w+)}cg){
my$first=$1
print"posis".pos($str)."\n"
}
if($str=~m{\GLastname:(\w+)}cg){
my$last=$1
print"posis".pos($str)."\n"
}
$str=~m{\GBookcollection:}cg

while($str=~m{\G\s*([^,]+),?}cg){
print"bookis'$1'\n"
print"posis".pos($str)."\n"
}
>posis16
>posis32
>bookis'ProgrammingPerl'
>posis65
>bookis'PerlCookbook'
>posis80
>bookis'ImpatientPerl'
>posis95

Anotherwaytocodetheabovescriptistousesubstitutionregularexpressionsandsubstitute
eachmatchedpartwithemptystrings.Theproblemisthatasubstitutioncreatesanewstring
andcopiestheremainingcharacterstothatstring,resultinginamuchslowerscript.Inthe
aboveexample,thespeeddifferencewouldnotbenoticeabletotheuser,butifyouhavea
scriptthatisparsingthroughalotoftext,thedifferencecanbequitesignificant.

20.11Modifiers
Regularexpressionscantakeoptionalmodifiersthattellperladditionalinformationabout
howtointerprettheregularexpression.Modifiersareplacedaftertheregularexpression,
outsideanycurlybraces.
$str=~m{pattern}modifiers
$str=~s{oldpatt}{newpatt}modifiers
$str=~tr{oldset}{newset}modifiers

20.11.1GlobalModifiers

Thefollowingmodifierscanbeusedwithm{},s{}{},ortr{}{}.
i

caseInsensitive,m{cat}imatchescat,Cat,CaT,CAt,CAT,etc

ignorespacesandtabsandcarriagereturnsinpattern.This
allowsthepatterntobespreadoutovermultiplelinesandfor
regularperlcommentstobeinsertedwithinthepatternbutbe
ignoredbytheregularexpressionengine.

treatstringasaSingleline.
"."willmatch"\n"withinthestring.
^and$positionanchorswillonlymatchliteralbeginningand
endofstring.

treatstringasMultiplelines.(DEFAULT)
"."willNOTmatch"\n"
^and$positionanchorswillmatchliteralbeginningandendof
stringandalso"\n"characterswithinthestring.
^and$indicatestart/endof"line"insteadofstart/endofstring.
^matchesafter"\n"
$matchesbefore"\n"

compilethepatternOnce.possiblespeedimprovement.

20.11.2ThemAndsModifiers

Thedefaultbehaviorofperlregularexpressionsis"m",treatingstringsasamultiplelines.If
neithera"m"or"s"modifierisusedonaregularexpression,perlwilldefaultto"m"
behavior.Ifthe"m"modifierisused,thenthe"^"anchorwillmatchthebeginningofthestring
or"\n"characters,the"$"anchorwillmatchtheendofthestringorany"\n"characters,and
the"."charactersetwillmatchanycharacterEXCEPT"\n".Ifastringcontainsmultiplelines
separatedby"\n",thenthedefaultbehavior(the"m"behavior)istotreatthestringasmultiple
lines,using"^"and"$"toindicatestartandendoflines.Ifthe"s"modifierisused,thenthe"^"
anchorwillonlymatchtheliteralbeginningofthestring,the"$"anchorwillonlymatchthe
literalendofstring,andthe"."classwillmatchanycharacterincluding"\n".Withthe"s"
modifier,evenifthestringismultiplelineswithembedded"\n"characters,the"s"modifier
forcesperltotreatitasasingleline.Thisexampleshowstheexactsamepatternboundto
theexactsamestring.Theonlydifferenceisthemodifierusedontheregularexpression.
Noticeinthe"s"version,thecapturedstringincludesthenewline"\n"characterswhich
showsupintheprintedoutput.Thesinglelineversionprintsoutthecapturedpatternacross
threedifferentlines.
my$string="Library:ProgrammingPerl\n"
."PerlCookbook\n"
."ImpatientPerl"
if($string=~m{Library:(.*)})
{print"defaultis'$1'\n"}
if($string=~m{Library:(.*)}m)
{print"multilineis'$1'\n"}
if($string=~m{Library:(.*)}s)
{print"singlelineis'$1'\n"}
>defaultis'ProgrammingPerl'
>multilineis'ProgrammingPerl'
>singlelineis'ProgrammingPerl
>PerlCookbook

>ImpatientPerl'

20.11.3ThexModifier
Thexmodifierallowsacomplexregularexpressionpatterntobespreadoutovermultiple
lines,withcomments,foreasierreading.Mostwhitespacewithinapatternwiththexmodifier
isignored.Thefollowingpatternislookingforanumberthatfollowsscientificnotation.The
patternisspreadoutovermultiplelineswithcommentstosupportmaintainability.
my$string='134.23423e12'
if($string=~m
{
^\s*([+]?)#positiveornegativeoroptional
\s*(\d+)#integerportion
(\.\d+)?#fractionalisoptional
(\s*e\s*[+]?\d+)?#exponentisoptional
}x){
my$sign=$1||''
my$integer=$2||''
my$fraction=$3||''
my$exponent=$4||''
print"signis'$sign'\n"
print"integeris'$integer'\n"
print"fractionis'$fraction'\n"
print"exponentis'$exponent'\n"
}
>signis''
>integeris'134'

>fractionis'.23423'
>exponentis'e12'

Acoupleofnotesfortheaboveexample:Thexmodifierstripsoutallspaces,tabs,and
carriagereturnsinthepattern.Ifthepatternexpectswhitespaceinthestring,itmustbe
explicitlystatedusing\sor\tor\norsomesimilarcharacterclass.Also,it'salwaysagood
ideatoanchoryourregularexpressionsomewhereinyourstring,with"^"or"$"or"\G".The
doublepipeexpressionsguaranteethatthevariablesareassignedtowhateverthepattern
matchedoremptystringifnomatchoccurred.Withoutthem,anunmatchedpatternmatch
willyieldan"undef"inthe$1(or$2or$3)variableassociatedwiththematch.

20.12ModifiersForm{}Operator
Thefollowingmodifiersapplytothem{pattern}operatoronly:
g

Globallyfindallmatchs.Withoutthismodifier,m{}willfind
thefirstoccurrenceofthepattern.

cg

ContinuesearchafterGlobalsearchfails.Thismaintainsthe
\Gmarkeratitslastmatchedposition.Withoutthismodifier,
the\Gmarkerisresettozeroifthepatterndoesnotmatch.

20.13Modifiersfors{}{}Operator
Thefollowingmodifiersapplytothes{oldpatt}{newpatt}operatoronly.
g

Globallyreplacealloccurrencesofoldpattwithnewpatt

interpretnewpattasaperlbasedstringExpression.
theresultoftheexpressionbecomesthereplacementstring.

20.14Modifiersfortr{}{}Operator

Thefollowingmodifiersapplytothetr{oldset}{newset}operatoronly.
c

Complementthesearchlist

Deletefoundbutunreplacedcharacters

Squashduplicatereplacedcharacters

20.15Theqr{}function
Theqr{}functiontakesastringandinterpretsitasaregularexpression,returningavalue
thatcanbestoredinascalarforpatternmatchingatalatertime.
my$number=qr{[+]?\s*\d+(?:\.\d+)?\s*(?:e\s*[+]?\s*\d+)?}

20.16CommonPatterns
Somesimpleandcommonregularexpressionpatternsareshownhere:
$str=~s{\s}{}g#removeallwhitespace
$str=~s{#.*}{}#removeperlcomments
nextif($str=~m{^\s*$})#nextifonlywhitespace

Forcommonbutmorecomplicatedregularexpressions,checkouttheRegexp::Common
moduleonCPAN.

20.17Regexp::Common
TheRegexp::Commonmodulecontainsmanycommon,butfairlycomplicated,regular
expressionpatterns(balancedparenthesesandbrackets,delimitedtextwithescapes,
integersandfloatingpointnumbersofdifferentbases,emailaddresses,andothers).Ifyou
aredoingsomecomplicatedpatternmatching,itmightbeworthamomenttocheckout
Regexp::Commonandseeifsomeonealreadydidtheworktomatchthepatternyouneed.
cpan>installRegexp::Common

OnceRegexp::Commonisinstalled,perlscriptsthatuseitwillhavea"magic"hashcalled

%REimportedintotheirnamespace.Thekeystothishasharehumanunderstandable
names,thedatainthehasharethepatternstousewithinregularexpressions.Hereishowto
findoutwhatthefloatingpointnumberpatternlookslikeinRegexp::Common:
useRegexp::Common
my$patt=$RE{num}{real}
print"$patt\n"
>(?:(?i)(?:[+]?)(?:(?=[0123456789]|[.])(?:
[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:
(?:[E])(?:(?:[+]?)(?:[0123456789]+))|))

Ascomplicatedasthisis,itisaloteasiertoreusesomeoneelse'scodethantotryand
reinventyourown,faulty,lopsided,wheel.Thehashlookupcanbeuseddirectlywithinyour
regularexpression:
useRegexp::Common
my$str="thisis12.423E42thenumber"
$str=~m{($RE{num}{real})}
print"matchis'$1'\n"
>matchis'12.423E42'

21ParsingwithParse::RecDescent
Perl'sregularexpressionpatternsaresufficientformanysituations,suchasextracting
informationoutofatabseparateddatabasethatisorganizedbylastname,firstname,dateof
birth,address,city,state,ZIP,phonenumber.Thedataisalwaysinafixedlocation,anda
regularexpressioncanbeusedtoperformsearcheswithinthatdata.Ifthedatabeingparsed
isnotquitesorigidinitsdefinition,regularexpressionsmaybecomeacumbersomemeans
toextractthedesireddata.Instead,theParse::RecDescentmodulemayproveusefulinthat
itallowswholegramaticalrulestobedefined,andthemoduleparsesthedataaccordingto
thoserules.
cpan>installParse::RecDescent

Parse::RecDescentdescribesitselfasamodulethatincrementallygeneratestopdownrecursive
descenttextparsersfromsimpleyacclikegrammarspecifications.Insimplerterms,
Parse::RecDescentusesregularexpressionstyledpatternstodefinegrammarrules,andtheserulescan
becombinedfairlyeasilytocreatecomplexrules.
HereisaquickexamplefromperldocParse::RecDescent
useParse::RecDescent
print"trytypingtheselines:\n"
print"He'sdead,Jim!\n"
print"Dammit,Jim,I'madoctor,nota
magician!\n"
print"press<CTL><D>whenfinished\n"
my$grammar=q{
McCoy:
curse","name",I'madoctor,nota"job"!"
{print"Justdowhatyoucan,Bones.\n"}
|pronoun"dead,"name"!"
{print"Shutup,Bones.\n"}
|<error>
curse:'Dammit'|'Goddammit'
name:'Jim'|'Spock'|'Scotty'
job:'magician'|'miracleworker'|'perlhacker'
pronoun:"He's"|"She's"|"It's"|"They're"
}
my$parse=newParse::RecDescent($grammar)
print">"

while(<>){
$parse>McCoy($_)
print">"
}
>trytypingtheselines:
>He'sdead,Jim!
>Dammit,Jim,I'madoctor,notamagician!
>press<CTL><D>whenfinished
>>Dammit,Jim,I'madoctor,notamagician!
>Justdowhatyoucan,Bones.
>>He'sdead,Jim!
>Shutup,Bones.
>>YougreenbloodedVulcan!
>
>ERROR(line1):InvalidMcCoy:
>Wasexpectingcurse,orpronoun

Parse::RecDescentisnotthesolutionforeverypatternmatchingproblem.
Parse::RecDescentisslowerthansimpleregularexpressions.Sinceitrecursivelydescends
throughitssetofrules,themorerules,thelongerittakestorun.Parse::RecDescent
currentlymustreadintheentiretextbeingparsed,whichcanbeaproblemifyouareparsing
agigabytesizedfile.AndParse::RecDescenthasanadditionallearningcurveaboveand
beyondperl'sregularexpressions.Parse::RecDescentusesperl"sregularexpression
patternsinitspatternmatching,soyouneedtolearnbasicregularexpressionpatterns
beforeyouuseParse::RecDescent.Ifthedatayouareminingisfairlycomplex,andnormal
regularexpressionsarebecomingdifficulttomanage,thenParse::RecDescentwouldbethe
nextlogicalmoduletolookat.

22Perl,GUI,andTk
Sofar,alltheexampleshavehadacommandlineinterface.Userinputandoutputoccurred
throughthesamecommandlineusedtoexecutetheperlscriptitself.PerlhasaGraphical
UserInterface(GUI)toolkitmoduleavailableonCPANcalledTk.
cpan>installTk

TheTkmoduleisaGUItoolkitthatcontainsaplethoraofbuttonsandlabelsandentryitems
andotherwidgetsneededtocreateagraphicaluserinterfacetoyourscripts.Onceinstalled,
theTkmodulehasawidgetdemonstrationprogramthatcanberunfromthecommandline
toseewhatwidgetsareavailableandwhattheylooklike.Atthecommandline,type"widget"
torunthedemonstrationprogram.
>widget

Hereisasimple"helloworld"styleprogramusingTk:
useTk
my$top=newMainWindow
$top>Button(
text=>"Hello",
command=>sub{print"Hi\n"}
)>grid(row=>1,column=>1)
MainLoop

Whentheaboveexampleisexecuted,asmallGUIwillpopuponthescreen(theMainWindowitem)
withabutton(the$top>Buttoncall)labeled"Hello"(thetextoption).Whenthemouseleftclickson
thebutton,theword"Hi"isprintedtothecommandline(thecommandoption).The>gridmethod
invokesthegeometrymanageronthewidgetandplacesitsomewhereintheGUI(withoutgeometry
management,thewidgetwillnotshowupintheGUI).TheMainLoopisasubroutinecallthatinvokes
theeventloop,drawingtheGUI,respondingtobuttonclicks,etc.
SeverallargebookshavebeenwrittenabouttheTkGUItoolkitforperl.Anditwouldbe
impossibletogiveanydecentintroductiontothismoduleinapageortwo.Ifyouplanon
creatingGUI'sinyourscripts,Irecommendthe"MasteringPerl/Tk"book.

23GNUFreeDocumentationLicense
GNUFreeDocumentationLicense
Version1.3,3November2008

Copyright(C)2000,2001,2002,2007,2008FreeSoftwareFoundation,Inc.
<http://fsf.org/>
Everyoneispermittedtocopyanddistributeverbatimcopies
ofthislicensedocument,butchangingitisnotallowed.
0.PREAMBLE
ThepurposeofthisLicenseistomakeamanual,textbook,orother
functionalandusefuldocument"free"inthesenseoffreedom:to
assureeveryonetheeffectivefreedomtocopyandredistributeit,
withorwithoutmodifyingit,eithercommerciallyornoncommercially.
Secondarily,thisLicensepreservesfortheauthorandpublisheraway
togetcreditfortheirwork,whilenotbeingconsideredresponsible
formodificationsmadebyothers.
ThisLicenseisakindof"copyleft",whichmeansthatderivative
worksofthedocumentmustthemselvesbefreeinthesamesense.It
complementstheGNUGeneralPublicLicense,whichisacopyleft
licensedesignedforfreesoftware.
WehavedesignedthisLicenseinordertouseitformanualsforfree
software,becausefreesoftwareneedsfreedocumentation:afree
programshouldcomewithmanualsprovidingthesamefreedomsthatthe
softwaredoes.ButthisLicenseisnotlimitedtosoftwaremanuals;
itcanbeusedforanytextualwork,regardlessofsubjectmatteror
whetheritispublishedasaprintedbook.WerecommendthisLicense
principallyforworkswhosepurposeisinstructionorreference.

1.APPLICABILITYANDDEFINITIONS
ThisLicenseappliestoanymanualorotherwork,inanymedium,that
containsanoticeplacedbythecopyrightholdersayingitcanbe
distributedunderthetermsofthisLicense.Suchanoticegrantsa
worldwide,royaltyfreelicense,unlimitedinduration,tousethat

workundertheconditionsstatedherein.The"Document",below,
referstoanysuchmanualorwork.Anymemberofthepublicisa
licensee,andisaddressedas"you".Youacceptthelicenseifyou
copy,modifyordistributetheworkinawayrequiringpermission
undercopyrightlaw.
A"ModifiedVersion"oftheDocumentmeansanyworkcontainingthe
Documentoraportionofit,eithercopiedverbatim,orwith
modificationsand/ortranslatedintoanotherlanguage.
A"SecondarySection"isanamedappendixorafrontmattersectionof
theDocumentthatdealsexclusivelywiththerelationshipofthe
publishersorauthorsoftheDocumenttotheDocument'soverall
subject(ortorelatedmatters)andcontainsnothingthatcouldfall
directlywithinthatoverallsubject.(Thus,iftheDocumentisin
partatextbookofmathematics,aSecondarySectionmaynotexplain
anymathematics.)Therelationshipcouldbeamatterofhistorical
connectionwiththesubjectorwithrelatedmatters,oroflegal,
commercial,philosophical,ethicalorpoliticalpositionregarding
them.
The"InvariantSections"arecertainSecondarySectionswhosetitles
aredesignated,asbeingthoseofInvariantSections,inthenotice
thatsaysthattheDocumentisreleasedunderthisLicense.Ifa
sectiondoesnotfittheabovedefinitionofSecondarythenitisnot
allowedtobedesignatedasInvariant.TheDocumentmaycontainzero
InvariantSections.IftheDocumentdoesnotidentifyanyInvariant
Sectionsthentherearenone.
The"CoverTexts"arecertainshortpassagesoftextthatarelisted,
asFrontCoverTextsorBackCoverTexts,inthenoticethatsaysthat
theDocumentisreleasedunderthisLicense.AFrontCoverTextmay
beatmost5words,andaBackCoverTextmaybeatmost25words.
A"Transparent"copyoftheDocumentmeansamachinereadablecopy,
representedinaformatwhosespecificationisavailabletothe
generalpublic,thatissuitableforrevisingthedocument
straightforwardlywithgenerictexteditorsor(forimagescomposedof
pixels)genericpaintprogramsor(fordrawings)somewidelyavailable
drawingeditor,andthatissuitableforinputtotextformattersor
forautomatictranslationtoavarietyofformatssuitableforinput

totextformatters.AcopymadeinanotherwiseTransparentfile
formatwhosemarkup,orabsenceofmarkup,hasbeenarrangedtothwart
ordiscouragesubsequentmodificationbyreadersisnotTransparent.
AnimageformatisnotTransparentifusedforanysubstantialamount
oftext.Acopythatisnot"Transparent"iscalled"Opaque".
ExamplesofsuitableformatsforTransparentcopiesincludeplain
ASCIIwithoutmarkup,Texinfoinputformat,LaTeXinputformat,SGML
orXMLusingapubliclyavailableDTD,andstandardconformingsimple
HTML,PostScriptorPDFdesignedforhumanmodification.Examplesof
transparentimageformatsincludePNG,XCFandJPG.Opaqueformats
includeproprietaryformatsthatcanbereadandeditedonlyby
proprietarywordprocessors,SGMLorXMLforwhichtheDTDand/or
processingtoolsarenotgenerallyavailable,andthe
machinegeneratedHTML,PostScriptorPDFproducedbysomeword
processorsforoutputpurposesonly.
The"TitlePage"means,foraprintedbook,thetitlepageitself,
plussuchfollowingpagesasareneededtohold,legibly,thematerial
thisLicenserequirestoappearinthetitlepage.Forworksin
formatswhichdonothaveanytitlepageassuch,"TitlePage"means
thetextnearthemostprominentappearanceofthework'stitle,
precedingthebeginningofthebodyofthetext.
The"publisher"meansanypersonorentitythatdistributescopiesof
theDocumenttothepublic.
Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhose
titleeitherispreciselyXYZorcontainsXYZinparenthesesfollowing
textthattranslatesXYZinanotherlanguage.(HereXYZstandsfora
specificsectionnamementionedbelow,suchas"Acknowledgements",
"Dedications","Endorsements",or"History".)To"PreservetheTitle"
ofsuchasectionwhenyoumodifytheDocumentmeansthatitremainsa
section"EntitledXYZ"accordingtothisdefinition.
TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhich
statesthatthisLicenseappliestotheDocument.TheseWarranty
Disclaimersareconsideredtobeincludedbyreferenceinthis
License,butonlyasregardsdisclaimingwarranties:anyother
implicationthattheseWarrantyDisclaimersmayhaveisvoidandhas
noeffectonthemeaningofthisLicense.

2.VERBATIMCOPYING
YoumaycopyanddistributetheDocumentinanymedium,either
commerciallyornoncommercially,providedthatthisLicense,the
copyrightnotices,andthelicensenoticesayingthisLicenseapplies
totheDocumentarereproducedinallcopies,andthatyouaddno
otherconditionswhatsoevertothoseofthisLicense.Youmaynotuse
technicalmeasurestoobstructorcontrolthereadingorfurther
copyingofthecopiesyoumakeordistribute.However,youmayaccept
compensationinexchangeforcopies.Ifyoudistributealargeenough
numberofcopiesyoumustalsofollowtheconditionsinsection3.
Youmayalsolendcopies,underthesameconditionsstatedabove,and
youmaypubliclydisplaycopies.

3.COPYINGINQUANTITY
Ifyoupublishprintedcopies(orcopiesinmediathatcommonlyhave
printedcovers)oftheDocument,numberingmorethan100,andthe
Document'slicensenoticerequiresCoverTexts,youmustenclosethe
copiesincoversthatcarry,clearlyandlegibly,alltheseCover
Texts:FrontCoverTextsonthefrontcover,andBackCoverTextson
thebackcover.Bothcoversmustalsoclearlyandlegiblyidentify
youasthepublisherofthesecopies.Thefrontcovermustpresent
thefulltitlewithallwordsofthetitleequallyprominentand
visible.Youmayaddothermaterialonthecoversinaddition.
Copyingwithchangeslimitedtothecovers,aslongastheypreserve
thetitleoftheDocumentandsatisfytheseconditions,canbetreated
asverbatimcopyinginotherrespects.
Iftherequiredtextsforeithercoveraretoovoluminoustofit
legibly,youshouldputthefirstoneslisted(asmanyasfit
reasonably)ontheactualcover,andcontinuetherestontoadjacent
pages.
IfyoupublishordistributeOpaquecopiesoftheDocumentnumbering
morethan100,youmusteitherincludeamachinereadableTransparent
copyalongwitheachOpaquecopy,orstateinorwitheachOpaquecopy
acomputernetworklocationfromwhichthegeneralnetworkusing

publichasaccesstodownloadusingpublicstandardnetworkprotocols
acompleteTransparentcopyoftheDocument,freeofaddedmaterial.
Ifyouusethelatteroption,youmusttakereasonablyprudentsteps,
whenyoubegindistributionofOpaquecopiesinquantity,toensure
thatthisTransparentcopywillremainthusaccessibleatthestated
locationuntilatleastoneyearafterthelasttimeyoudistributean
Opaquecopy(directlyorthroughyouragentsorretailers)ofthat
editiontothepublic.
Itisrequested,butnotrequired,thatyoucontacttheauthorsofthe
Documentwellbeforeredistributinganylargenumberofcopies,to
givethemachancetoprovideyouwithanupdatedversionofthe
Document.

4.MODIFICATIONS
YoumaycopyanddistributeaModifiedVersionoftheDocumentunder
theconditionsofsections2and3above,providedthatyourelease
theModifiedVersionunderpreciselythisLicense,withtheModified
VersionfillingtheroleoftheDocument,thuslicensingdistribution
andmodificationoftheModifiedVersiontowhoeverpossessesacopy
ofit.Inaddition,youmustdothesethingsintheModifiedVersion:
A.UseintheTitlePage(andonthecovers,ifany)atitledistinct
fromthatoftheDocument,andfromthoseofpreviousversions
(whichshould,iftherewereany,belistedintheHistorysection
oftheDocument).Youmayusethesametitleasapreviousversion
iftheoriginalpublisherofthatversiongivespermission.
B.ListontheTitlePage,asauthors,oneormorepersonsorentities
responsibleforauthorshipofthemodificationsintheModified
Version,togetherwithatleastfiveoftheprincipalauthorsofthe
Document(allofitsprincipalauthors,ifithasfewerthanfive),
unlesstheyreleaseyoufromthisrequirement.
C.StateontheTitlepagethenameofthepublisherofthe
ModifiedVersion,asthepublisher.
D.PreserveallthecopyrightnoticesoftheDocument.
E.Addanappropriatecopyrightnoticeforyourmodifications
adjacenttotheothercopyrightnotices.
F.Include,immediatelyafterthecopyrightnotices,alicensenotice
givingthepublicpermissiontousetheModifiedVersionunderthe

termsofthisLicense,intheformshownintheAddendumbelow.
G.PreserveinthatlicensenoticethefulllistsofInvariantSections
andrequiredCoverTextsgivenintheDocument'slicensenotice.
H.IncludeanunalteredcopyofthisLicense.
I.PreservethesectionEntitled"History",PreserveitsTitle,andadd
toitanitemstatingatleastthetitle,year,newauthors,and
publisheroftheModifiedVersionasgivenontheTitlePage.If
thereisnosectionEntitled"History"intheDocument,createone
statingthetitle,year,authors,andpublisheroftheDocumentas
givenonitsTitlePage,thenaddanitemdescribingtheModified
Versionasstatedintheprevioussentence.
J.Preservethenetworklocation,ifany,givenintheDocumentfor
publicaccesstoaTransparentcopyoftheDocument,andlikewise
thenetworklocationsgivenintheDocumentforpreviousversions
itwasbasedon.Thesemaybeplacedinthe"History"section.
Youmayomitanetworklocationforaworkthatwaspublishedat
leastfouryearsbeforetheDocumentitself,oriftheoriginal
publisheroftheversionitreferstogivespermission.
K.ForanysectionEntitled"Acknowledgements"or"Dedications",
PreservetheTitleofthesection,andpreserveinthesectionall
thesubstanceandtoneofeachofthecontributoracknowledgements
and/ordedicationsgiventherein.
L.PreservealltheInvariantSectionsoftheDocument,
unalteredintheirtextandintheirtitles.Sectionnumbers
ortheequivalentarenotconsideredpartofthesectiontitles.
M.DeleteanysectionEntitled"Endorsements".Suchasection
maynotbeincludedintheModifiedVersion.
N.DonotretitleanyexistingsectiontobeEntitled"Endorsements"
ortoconflictintitlewithanyInvariantSection.
O.PreserveanyWarrantyDisclaimers.
IftheModifiedVersionincludesnewfrontmattersectionsor
appendicesthatqualifyasSecondarySectionsandcontainnomaterial
copiedfromtheDocument,youmayatyouroptiondesignatesomeorall
ofthesesectionsasinvariant.Todothis,addtheirtitlestothe
listofInvariantSectionsintheModifiedVersion'slicensenotice.
Thesetitlesmustbedistinctfromanyothersectiontitles.
YoumayaddasectionEntitled"Endorsements",provideditcontains
nothingbutendorsementsofyourModifiedVersionbyvarious
partiesforexample,statementsofpeerrevieworthatthetexthas

beenapprovedbyanorganizationastheauthoritativedefinitionofa
standard.
YoumayaddapassageofuptofivewordsasaFrontCoverText,anda
passageofupto25wordsasaBackCoverText,totheendofthelist
ofCoverTextsintheModifiedVersion.Onlyonepassageof
FrontCoverTextandoneofBackCoverTextmaybeaddedby(or
througharrangementsmadeby)anyoneentity.IftheDocumentalready
includesacovertextforthesamecover,previouslyaddedbyyouor
byarrangementmadebythesameentityyouareactingonbehalfof,
youmaynotaddanother;butyoumayreplacetheoldone,onexplicit
permissionfromthepreviouspublisherthataddedtheoldone.
Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicense
givepermissiontousetheirnamesforpublicityforortoassertor
implyendorsementofanyModifiedVersion.

5.COMBININGDOCUMENTS
YoumaycombinetheDocumentwithotherdocumentsreleasedunderthis
License,underthetermsdefinedinsection4aboveformodified
versions,providedthatyouincludeinthecombinationallofthe
InvariantSectionsofalloftheoriginaldocuments,unmodified,and
listthemallasInvariantSectionsofyourcombinedworkinits
licensenotice,andthatyoupreservealltheirWarrantyDisclaimers.
ThecombinedworkneedonlycontainonecopyofthisLicense,and
multipleidenticalInvariantSectionsmaybereplacedwithasingle
copy.IftherearemultipleInvariantSectionswiththesamenamebut
differentcontents,makethetitleofeachsuchsectionuniqueby
addingattheendofit,inparentheses,thenameoftheoriginal
authororpublisherofthatsectionifknown,orelseauniquenumber.
Makethesameadjustmenttothesectiontitlesinthelistof
InvariantSectionsinthelicensenoticeofthecombinedwork.
Inthecombination,youmustcombineanysectionsEntitled"History"
inthevariousoriginaldocuments,formingonesectionEntitled
"History";likewisecombineanysectionsEntitled"Acknowledgements",
andanysectionsEntitled"Dedications".Youmustdeleteallsections
Entitled"Endorsements".

6.COLLECTIONSOFDOCUMENTS
YoumaymakeacollectionconsistingoftheDocumentandother
documentsreleasedunderthisLicense,andreplacetheindividual
copiesofthisLicenseinthevariousdocumentswithasinglecopy
thatisincludedinthecollection,providedthatyoufollowtherules
ofthisLicenseforverbatimcopyingofeachofthedocumentsinall
otherrespects.
Youmayextractasingledocumentfromsuchacollection,and
distributeitindividuallyunderthisLicense,providedyouinserta
copyofthisLicenseintotheextracteddocument,andfollowthis
Licenseinallotherrespectsregardingverbatimcopyingofthat
document.

7.AGGREGATIONWITHINDEPENDENTWORKS
AcompilationoftheDocumentoritsderivativeswithotherseparate
andindependentdocumentsorworks,inoronavolumeofastorageor
distributionmedium,iscalledan"aggregate"ifthecopyright
resultingfromthecompilationisnotusedtolimitthelegalrights
ofthecompilation'susersbeyondwhattheindividualworkspermit.
WhentheDocumentisincludedinanaggregate,thisLicensedoesnot
applytotheotherworksintheaggregatewhicharenotthemselves
derivativeworksoftheDocument.
IftheCoverTextrequirementofsection3isapplicabletothese
copiesoftheDocument,theniftheDocumentislessthanonehalfof
theentireaggregate,theDocument'sCoverTextsmaybeplacedon
coversthatbrackettheDocumentwithintheaggregate,orthe
electronicequivalentofcoversiftheDocumentisinelectronicform.
Otherwisetheymustappearonprintedcoversthatbracketthewhole
aggregate.

8.TRANSLATION
Translationisconsideredakindofmodification,soyoumay

distributetranslationsoftheDocumentunderthetermsofsection4.
ReplacingInvariantSectionswithtranslationsrequiresspecial
permissionfromtheircopyrightholders,butyoumayinclude
translationsofsomeorallInvariantSectionsinadditiontothe
originalversionsoftheseInvariantSections.Youmayincludea
translationofthisLicense,andallthelicensenoticesinthe
Document,andanyWarrantyDisclaimers,providedthatyoualsoinclude
theoriginalEnglishversionofthisLicenseandtheoriginalversions
ofthosenoticesanddisclaimers.Incaseofadisagreementbetween
thetranslationandtheoriginalversionofthisLicenseoranotice
ordisclaimer,theoriginalversionwillprevail.
IfasectionintheDocumentisEntitled"Acknowledgements",
"Dedications",or"History",therequirement(section4)toPreserve
itsTitle(section1)willtypicallyrequirechangingtheactual
title.

9.TERMINATION
Youmaynotcopy,modify,sublicense,ordistributetheDocument
exceptasexpresslyprovidedunderthisLicense.Anyattempt
otherwisetocopy,modify,sublicense,ordistributeitisvoid,and
willautomaticallyterminateyourrightsunderthisLicense.
However,ifyouceaseallviolationofthisLicense,thenyourlicense
fromaparticularcopyrightholderisreinstated(a)provisionally,
unlessanduntilthecopyrightholderexplicitlyandfinally
terminatesyourlicense,and(b)permanently,ifthecopyrightholder
failstonotifyyouoftheviolationbysomereasonablemeanspriorto
60daysafterthecessation.
Moreover,yourlicensefromaparticularcopyrightholderis
reinstatedpermanentlyifthecopyrightholdernotifiesyouofthe
violationbysomereasonablemeans,thisisthefirsttimeyouhave
receivednoticeofviolationofthisLicense(foranywork)fromthat
copyrightholder,andyoucuretheviolationpriorto30daysafter
yourreceiptofthenotice.
Terminationofyourrightsunderthissectiondoesnotterminatethe
licensesofpartieswhohavereceivedcopiesorrightsfromyouunder

thisLicense.Ifyourrightshavebeenterminatedandnotpermanently
reinstated,receiptofacopyofsomeorallofthesamematerialdoes
notgiveyouanyrightstouseit.

10.FUTUREREVISIONSOFTHISLICENSE
TheFreeSoftwareFoundationmaypublishnew,revisedversionsofthe
GNUFreeDocumentationLicensefromtimetotime.Suchnewversions
willbesimilarinspirittothepresentversion,butmaydifferin
detailtoaddressnewproblemsorconcerns.See
http://www.gnu.org/copyleft/.
EachversionoftheLicenseisgivenadistinguishingversionnumber.
IftheDocumentspecifiesthataparticularnumberedversionofthis
License"oranylaterversion"appliestoit,youhavetheoptionof
followingthetermsandconditionseitherofthatspecifiedversionor
ofanylaterversionthathasbeenpublished(notasadraft)bythe
FreeSoftwareFoundation.IftheDocumentdoesnotspecifyaversion
numberofthisLicense,youmaychooseanyversioneverpublished(not
asadraft)bytheFreeSoftwareFoundation.IftheDocument
specifiesthataproxycandecidewhichfutureversionsofthis
Licensecanbeused,thatproxy'spublicstatementofacceptanceofa
versionpermanentlyauthorizesyoutochoosethatversionforthe
Document.
11.RELICENSING
"MassiveMultiauthorCollaborationSite"(or"MMCSite")meansany
WorldWideWebserverthatpublishescopyrightableworksandalso
providesprominentfacilitiesforanybodytoeditthoseworks.A
publicwikithatanybodycaneditisanexampleofsuchaserver.A
"MassiveMultiauthorCollaboration"(or"MMC")containedinthesite
meansanysetofcopyrightableworksthuspublishedontheMMCsite.
"CCBYSA"meanstheCreativeCommonsAttributionShareAlike3.0
licensepublishedbyCreativeCommonsCorporation,anotforprofit
corporationwithaprincipalplaceofbusinessinSanFrancisco,
California,aswellasfuturecopyleftversionsofthatlicense
publishedbythatsameorganization.

"Incorporate"meanstopublishorrepublishaDocument,inwholeorin
part,aspartofanotherDocument.
AnMMCis"eligibleforrelicensing"ifitislicensedunderthis
License,andifallworksthatwerefirstpublishedunderthisLicense
somewhereotherthanthisMMC,andsubsequentlyincorporatedinwholeor
inpartintotheMMC,(1)hadnocovertextsorinvariantsections,and
(2)werethusincorporatedpriortoNovember1,2008.
TheoperatorofanMMCSitemayrepublishanMMCcontainedinthesite
underCCBYSAonthesamesiteatanytimebeforeAugust1,2009,
providedtheMMCiseligibleforrelicensing.

ADDENDUM:HowtousethisLicenseforyourdocuments
TousethisLicenseinadocumentyouhavewritten,includeacopyof
theLicenseinthedocumentandputthefollowingcopyrightand
licensenoticesjustafterthetitlepage:
Copyright(c)YEARYOURNAME.
Permissionisgrantedtocopy,distributeand/ormodifythisdocument
underthetermsoftheGNUFreeDocumentationLicense,Version1.3
oranylaterversionpublishedbytheFreeSoftwareFoundation;
withnoInvariantSections,noFrontCoverTexts,andnoBackCoverTexts.
Acopyofthelicenseisincludedinthesectionentitled"GNU
FreeDocumentationLicense".
IfyouhaveInvariantSections,FrontCoverTextsandBackCoverTexts,
replacethe"with...Texts."linewiththis:
withtheInvariantSectionsbeingLISTTHEIRTITLES,withthe
FrontCoverTextsbeingLIST,andwiththeBackCoverTextsbeingLIST.
IfyouhaveInvariantSectionswithoutCoverTexts,orsomeother
combinationofthethree,mergethosetwoalternativestosuitthe
situation.
Ifyourdocumentcontainsnontrivialexamplesofprogramcode,we
recommendreleasingtheseexamplesinparallelunderyourchoiceof
freesoftwarelicense,suchastheGNUGeneralPublicLicense,

topermittheiruseinfreesoftware.
AlphabeticalIndex
abs16
AND26
anonymous51
anonymoussubroutine70
anonymoussubroutines69
argumentpassing70
array32
@32
$32
Autovivification54
backtick112
baseconversion21
BEGIN76
bless83p.
bless/constructors96
blessREFERENCE,STRING83
blessedinvocant89
boolean23
caller74
can88
CapturingandClusteringParenthesis118
CharacterClasses119

CHECK76
chomp13
class92
clone56
close108
closures66
cmp25
codereference71
codereuse78
commandline
Getopt::Declare105
@ARGV103
CommandLineArguments102
comparison25
comparisonoperator25
compiling76
complexdatastructures53
concatenation13
conditionaloperator28
continue59
controlflow59
cos17
CPAN98

CPAN,ThePerlModule98
CPAN,TheWebSite98
CreatingModules101
DataPersistence56
dclone56
deepclone56
defined22
delete42
dereference50
dereferencingcodereferences71
doublequote12
e18
each43
else59
elsif59
END76
eq25
equalto25
executiontimeline82
exists41
exp18
exponentiation17
false23p.

fileglob110
FileInputandOutput108
FileIO
close108
open108
read108
write109
FileTest
d110
e110
f110
l110
p110
r110
S110
T110
w110
z110
FileTests110
File::Find111
for59
foreach36,59
garbagecollection64p.

ge25
Getopt::Declare105
glob110
GlobalModifiers125
GlobalModifiers(regularexpressions)125
greaterthan25
greaterthanorequalto25
Greedy(Maximal)Quantifiers121
gt25
GUIandPerl::Tk133
h2xs101
hash39
$40
heredocument15
hex21
hexadecimal16
if59
imaginarynumbers17
import79pp.
Inheritance86,97
INIT76
int16
interpreting76

INVOCANT>METHOD85
INVOCANT>can(METHODNAME)88
INVOCANT>isa(BASEPACKAGE)88
isa88
join14
keys42
label60
last60
le25
length13
lessthan25
lessthanorequalto25
lexicalscope63
lexicalvariable63
list47
literal
binary16
hexadecimal16
octal16
string12
local68
log18
log_x_base_b18

logicaloperators26
lt25
m/patt/113
Math::Complex17
Math::Trig17
MetacharactersWithinCharacterClasses120
methodcalls85
Methods97
Modules96
multidimensionalarray55
multilinestring15
namedreferent50
namedsubroutine69
namedsubroutines69
namespace61
naturallogarithms18
ne25
next60
NOT26
notequalto25
nstore56
numbers16
numeric

literal16
rounding17
numify20
ObjectDestruction95
objectorientedperl83
ObjectOrientedPerl90
ObjectOrientedReview96
oct21
octal16
open108
OperatingSystemCommands112
backtick112
system112
Tk::ExecuteCommand112
`112
OR26
our62
OverridingMethods97
package61
packagemain61
packagequalifiedvariable61
Parse::RecDescent130
perlmodules78

PERL5LIB80
perldoc101
PlainOldDocumentation101
POD101
Polymorphism92
pop34
PositionAssertions/PositionAnchors122
push34
quote
doube12
single12
qw12,15
rand18
randomnumbers18
read108
redo60
ref57,84
reference49
referent49,84
Regexp::Common129
RegularExpressions113
acharacterclass116
alternation116

capturing116
CapturingandClusteringParenthesis118
CharacterClasses119
clustering116
DefiningaPattern115
GlobalModifiers125
Greedy(Maximal)Quantifiers121
grouping116
m/patt/113
Metacharacters116
PositionAssertions/PositionAnchors122
quantifier116
ShortcutCharacterClasses120
Thrifty(Minimal)Quantifiers121
VariableInterpolation114
WildcardExample115
!~113
=~113
$1,$2,$3118
repetition13
require79p.
retrieve56
return73

reuse78
reverse38
rounding17
scalar11,33
Autovivify12
numbers16
string12
$11
shift35
ShortcutCharacterClasses120
sin17
singlequote12
sort37
spaceshipoperator25
splice39
split14
sprintf19
sqrt17
srand18
Storable.pm56
string
doublequote12
singlequote12

stringify19
subroutine
argumentpassing70
subroutineclosures66
subroutinereturnvalue73
subroutines69
anonymous69
closures66
named69
substr13
SUPER97
SUPER::93
system112
tan17
ternaryoperator28
Thrifty(Minimal)Quantifiers121
Tk::ExecuteCommand112
trigonometry17
trinaryoperator28
true23p.
undefined22
unless59
unshift35

use78
usebaseMODULENAME87
uselib80
useModule96
useMODULENAME79
values43
wantarray75
while59
write109
xor26
XOR26
d110
e110
f110
l110
p110
r110
S110
T110
w110
x110
z110
:28

!26
!=25
!~113
?28
'12
"12
[]119
@32
@_71
@ARGV103
@INC79
@ISA87
**17
\b122
\G123
&&26
<25
<<15
<=25
<=>25
<$fh>109
==25
=~113

>25
>=25
||26
$11
scalar11
$1,$2,$3118

Вам также может понравиться