Teach Yourself PERL 5 in 21 Days [2nd ed.] 0672308940, 9780672308949

Teach Yourself Perl 5 in 21 Days, Second Edition is the ideal book for beginning - and intermediate - level users who wa

172 79 4MB

English Pages 1124 Year 1996

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Perl Book......Page 0
Table of Contents......Page 1
Week 1 -- At a Glance......Page 30
Day 1 -- Getting Started......Page 32
Day 2 -- Basic Operators and Control Flow......Page 53
Day 3 -- Understanding Scalar Values......Page 92
Day 4 -- More Operators......Page 116
Day 5 -- Lists and Array Variables......Page 172
Day 6 -- Reading from and Writing to Files......Page 236
Day 7 -- Pattern Matching......Page 287
Week 1 -- In Review......Page 357
Week 2 -- At a Glance......Page 363
Day 8 -- More Control Structures......Page 365
Day 9 -- Using Subroutines......Page 408
Day 10 -- Associative Arrays......Page 460
Day 11 -- Formatting Your Output......Page 501
Day 12 -- Working with the File System......Page 544
Day 13 -- Process, String, and Mathematical Functions......Page 598
Day 14 -- Scalar-Conversion and List-Manipulation Functions......Page 650
Week 2 -- In Review......Page 722
Week 3 -- At a Glance......Page 735
Day 15 -- System Functions......Page 737
Day 16 -- Command-Line Options......Page 796
Day 17 -- System Variables......Page 843
Day 18 -- References in Perl 5......Page 904
Day 19 -- Object-Oriented Programming in Perl......Page 937
Day 20 -- Miscellaneous Features of Perl......Page 969
Day 21 -- The Perl Debugger......Page 1006
Week 3 -- In Review......Page 1035
Appendix A -- Answers......Page 1047
Appendix B -- ASCII Character Set......Page 1107
Recommend Papers

Teach Yourself PERL 5 in 21 Days [2nd ed.]
 0672308940, 9780672308949

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

Teach Yourself Perl 5 in 21 days David Till

Table of Contents: Introduction ● ● ● ● ● ●

Wh o Sh ou l d Rea d Th is Book? Specia l Fea t u r es of Th is Book Pr ogr a mmin g Exa mpl es En d-of -Da y Q& A a n d Wor ksh op Con ven t ion s Used in Th is Book Wh a t You 'l l Lea r n in 21 Da ys

Week 1 Week at a Glance ●

Wh er e You 'r e Goin g

Day 1 Getting Started ● ●

● ●









Wh a t Is Per l ? How Do I Fin d Per l ? ❍ Wh er e Do I Get Per l ? ❍ Ot h er Pl a ces t o Get Per l A Sa mpl e Per l Pr ogr a m Ru n n in g a Per l Pr ogr a m ❍ If Somet h in g Goes Wr on g Th e Fir st Lin e of You r Per l Pr ogr a m: How Commen t s Wor k ❍ Commen t s Lin e 2: St a t emen t s, Token s, a n d ❍ St a t emen t s a n d Token s ❍ Token s a n d Wh it e Spa ce ❍ Wh a t t h e Token s Do: Rea din g f r om St a n da r d In pu t Lin e 3: Wr it in g t o St a n da r d Ou t pu t ❍ Fu n ct ion In voca t ion s a n d Ar gu men t s Er r or Messa ges

● ● ● ●

In t er pr et ive La n gu a ges Ver su s Compil ed La n gu a ges Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 2 Basic Operators and Control Flow ●





● ● ●

● ● ● ● ● ● ● ●

St or in g in Sca l a r Va r ia bl es Assign men t ❍ Th e Def in it ion of a Sca l a r Va r ia bl e ❍ Sca l a r Va r ia bl e Syn t a x ❍ Assign in g a Va l u e t o a Sca l a r Va r ia bl e Per f or min g Ar it h met ic ❍ Exa mpl e of Mil es-t o-Kil omet er s Con ver sion ❍ Th e chop Libr a r y Fu n ct ion Expr ession s ❍ Assign men t s a n d Expr ession s Ot h er Per l Oper a t or s In t r odu ct ion t o Con dit ion a l St a t emen t s Th e if St a t emen t ❍ Th e Con dit ion a l Expr ession ❍ Th e St a t emen t Bl ock ❍ Test in g f or Equ a l it y Usin g == ❍ Ot h er Compa r ison Oper a t or s Two-Wa y Br a n ch in g Usin g if a n d else Mu l t i-Wa y Br a n ch in g Usin g elsif Wr it in g Loops Usin g t h e while St a t emen t Nest in g Con dit ion a l St a t emen t s Loopin g Usin g t h e until St a t emen t Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 3 Understanding Scalar Values ● ●

Wh a t Is a Sca l a r Va l u e? In t eger Sca l a r Va l u es ❍ In t eger Sca l a r Va l u e Limit a t ion s









● ● ●

Fl oa t in g-Poin t Sca l a r Va l u es ❍ Fl oa t in g-Poin t Ar it h met ic a n d Rou n d-Of f Er r or Usin g Oct a l a n d Hexa decima l Not a t ion ❍ Decima l Not a t ion ❍ Oct a l Not a t ion ❍ Hexa decima l Not a t ion ❍ Wh y Bot h er ? Ch a r a ct er St r in gs ❍ Usin g Dou bl e-Qu ot ed St r in gs ❍ Esca pe Sequ en ces ❍ Sin gl e-Qu ot ed St r in gs In t er ch a n gea bil it y of St r in gs a n d Nu mer ic Va l u es ❍ In it ia l Va l u es of Sca l a r Va r ia bl es Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 4 More Operators ●











Usin g t h e Ar it h met ic Oper a t or s ❍ Expon en t ia t ion ❍ Th e Rema in der Oper a t or ❍ Un a r y Nega t ion Usin g Compa r ison Oper a t or s ❍ In t eger -Compa r ison Oper a t or s ❍ St r in g-Compa r ison Oper a t or s ❍ St r in g Compa r ison Ver su s In t eger Compa r ison ❍ Compa r ison a n d Fl oa t in g-Poin t Nu mber s Usin g Logica l Oper a t or s ❍ Eva l u a t ion Wit h in Logica l Oper a t or s ❍ Logica l Oper a t or s a s Su bexpr ession s Usin g Bit -Ma n ipu l a t ion Oper a t or s ❍ Wh a t Bit s Ar e a n d How Th ey Ar e Used ❍ Th e Bit -Ma n ipu l a t ion Oper a t or s Usin g t h e Assign men t Oper a t or s ❍ Assign men t Oper a t or s a s Su bexpr ession s Usin g Au t oin cr emen t a n d Au t odecr emen t ❍ Th e Au t oin cr emen t Oper a t or Pr e-In cr emen t ❍ Th e Au t oin cr emen t Oper a t or Post -In cr emen t

Th e Au t odecr emen t Oper a t or ❍ Usin g Au t oin cr emen t Wit h St r in gs Th e St r in g Con ca t en a t ion a n d Repet it ion Oper a t or s ❍ Th e St r in g-Con ca t en a t ion Oper a t or ❍ Th e St r in g-Repet it ion Oper a t or ❍ Con ca t en a t ion a n d Assign men t Ot h er Per l Oper a t or s ❍ Th e Comma Oper a t or ❍ Th e Con dit ion a l Oper a t or Th e Or der of Oper a t ion s ❍ Pr eceden ce ❍ Associa t ivit y ❍ For cin g Pr eceden ce Usin g Pa r en t h eses Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍







● ● ●

Day 5 Lists and Array Variables ● ●

● ●







● ●

In t r odu cin g List s Sca l a r Va r ia bl es a n d List s ❍ List s a n d St r in g Su bst it u t ion St or in g List s in Ar r a y Va r ia bl es Accessin g a n El emen t of a n Ar r a y Va r ia bl e ❍ Mor e Det a il s on Ar r a y El emen t Na mes Usin g List s a n d Ar r a ys in Per l Pr ogr a ms ❍ Usin g Br a cket s a n d Su bst it u t in g f or Va r ia bl es Usin g List Ra n ges ❍ Expr ession s a n d List Ra n ges Mor e on Assign men t a n d Ar r a y Va r ia bl es ❍ Copyin g f r om On e Ar r a y Va r ia bl e t o An ot h er ❍ Usin g Ar r a y Va r ia bl es in List s ❍ Su bst it u t in g f or Ar r a y Va r ia bl es in St r in gs ❍ Assign in g t o Sca l a r Va r ia bl es f r om Ar r a y Va r ia bl es Ret r ievin g t h e Len gt h of a List Usin g Ar r a y Sl ices ❍ Usin g List Ra n ges in Ar r a y-Sl ice Su bscr ipt s ❍ Usin g Va r ia bl es in Ar r a y-Sl ice Su bscr ipt s ❍ Assign in g t o Ar r a y Sl ices

Over l a ppin g Ar r a y Sl ices ❍ Usin g t h e Ar r a y-Sl ice Not a t ion a s a Sh or t h a n d Rea din g a n Ar r a y f r om t h e St a n da r d In pu t Fil e Ar r a y Libr a r y Fu n ct ion s ❍ Sor t in g a List or Ar r a y Va r ia bl e ❍ Rever sin g a List or Ar r a y Va r ia bl e ❍ Usin g chop on Ar r a y Va r ia bl es ❍ Cr ea t in g a Sin gl e St r in g f r om a List ❍ Spl it t in g a St r in g in t o a List ❍ Ot h er List -Ma n ipu l a t ion Fu n ct ion s Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍

● ●

● ● ●

Day 6 Reading from and Writing to Files ●





● ● ● ●

Open in g a Fil e ❍ Th e Fil e Va r ia bl e ❍ Th e Fil en a me ❍ Th e Fil e Mode ❍ Ch eckin g Wh et h er t h e Open Su cceeded Rea din g f r om a Fil e ❍ Fil e Va r ia bl es a n d t h e St a n da r d In pu t Fil e ❍ Ter min a t in g a Pr ogr a m Usin g die ❍ Rea din g in t o Ar r a y Va r ia bl es Wr it in g t o a Fil e ❍ Th e St a n da r d Ou t pu t Fil e Va r ia bl e ❍ Mer gin g Two Fil es in t o On e Redir ect in g St a n da r d In pu t a n d St a n da r d Ou t pu t Th e St a n da r d Er r or Fil e Cl osin g a Fil e Det er min in g t h e St a t u s of a Fil e ❍ Fil e-Test Oper a t or Syn t a x ❍ Ava il a bl e Fil e-Test Oper a t or s ❍ Mor e on t h e -e Oper a t or ❍ Test in g f or Rea d Per mission -t h e -r Oper a t or ❍ Ch eckin g f or Ot h er Per mission s ❍ Ch eckin g f or Empt y Fil es ❍ Usin g Fil e-Test Oper a t or s wit h Fil e Va r ia bl es





● ● ● ●

Rea din g f r om a Sequ en ce of Fil es ❍ Rea din g in t o a n Ar r a y Va r ia bl e Usin g Comma n d-Lin e Ar gu men t s a s Va l u es ❍ ARGV a n d t h e Oper a t or Open in g Pipes Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 7 Pattern Matching ● ●







In t r odu ct ion Th e Ma t ch Oper a t or s ❍ Ma t ch -Oper a t or Pr eceden ce Specia l Ch a r a ct er s in Pa t t er n s ❍ Th e + Ch a r a ct er ❍ Th e [] Specia l Ch a r a ct er s ❍ Th e * a n d ? Specia l Ch a r a ct er s ❍ Esca pe Sequ en ces f or Specia l Ch a r a ct er s ❍ Ma t ch in g An y Let t er or Nu mber ❍ An ch or in g Pa t t er n s ❍ Va r ia bl e Su bst it u t ion in Pa t t er n s ❍ Excl u din g Al t er n a t ives ❍ Ch a r a ct er -Ra n ge Esca pe Sequ en ces ❍ Ma t ch in g An y Ch a r a ct er ❍ Ma t ch in g a Specif ied Nu mber of Occu r r en ces ❍ Specif yin g Ch oices ❍ Reu sin g Por t ion s of Pa t t er n s ❍ Pa t t er n -Sequ en ce Sca l a r Va r ia bl es ❍ Specia l -Ch a r a ct er Pr eceden ce ❍ Specif yin g a Dif f er en t Pa t t er n Del imit er Pa t t er n -Ma t ch in g Opt ion s ❍ Ma t ch in g Al l Possibl e Pa t t er n s ❍ Ign or in g Ca se ❍ Tr ea t in g t h e St r in g a s Mu l t ipl e Lin es ❍ Eva l u a t in g a Pa t t er n On l y On ce ❍ Tr ea t in g t h e St r in g a s a Sin gl e Lin e ❍ Usin g Wh it e Spa ce in Pa t t er n s Th e Su bst it u t ion Oper a t or

Usin g Pa t t er n -Sequ en ce Va r ia bl es in Su bst it u t ion s ❍ Opt ion s f or t h e Su bst it u t ion Oper a t or ❍ Eva l u a t in g a Pa t t er n On l y On ce ❍ Tr ea t in g t h e St r in g a s Sin gl e or Mu l t ipl e Lin es ❍ Usin g Wh it e Spa ce in Pa t t er n s ❍ Specif yin g a Dif f er en t Del imit er Th e Tr a n sl a t ion Oper a t or ❍ Opt ion s f or t h e Tr a n sl a t ion Oper a t or Ext en ded Pa t t er n -Ma t ch in g ❍ Pa r en t h esiz in g Wit h ou t Sa vin g in Memor y ❍ Embeddin g Pa t t er n Opt ion s ❍ Posit ive a n d Nega t ive Look-Ah ea d ❍ Pa t t er n Commen t s Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍





● ● ●

Week 1 Week 1 in Review Week 2 Week 2 at a Glance ●

Wh er e You 'r e Goin g

Day 8 More Control Structures ●





● ● ● ● ●

Usin g Sin gl e-Lin e Con dit ion a l St a t emen t s ❍ Pr obl ems wit h Sin gl e-Lin e Con dit ion a l St a t emen t s Loopin g Usin g t h e for St a t emen t ❍ Usin g t h e Comma Oper a t or in a for St a t emen t Loopin g Th r ou gh a List : Th e foreach St a t emen t ❍ Th e foreach Loca l Va r ia bl e ❍ Ch a n gin g t h e Va l u e of t h e Loca l Va r ia bl e ❍ Usin g Ret u r n ed List s in t h e foreach St a t emen t Th e do St a t emen t Exit in g a Loop Usin g t h e last St a t emen t Usin g next t o St a r t t h e Next It er a t ion of a Loop Th e redo St a t emen t Usin g La bel ed Bl ocks f or Mu l t il evel Ju mps

Usin g next a n d redo wit h La bel s Th e continue Bl ock Th e goto St a t emen t Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍

● ● ● ● ●

Day 9 Using Subroutines ● ●



● ●



● ● ● ● ● ●

● ● ●

Wh a t Is a Su br ou t in e? Def in in g a n d In vokin g a Su br ou t in e ❍ For wa r d Ref er en ces t o Su br ou t in es Ret u r n in g a Va l u e f r om a Su br ou t in e ❍ Ret u r n Va l u es a n d Con dit ion a l Expr ession s Th e return St a t emen t Usin g Loca l Va r ia bl es in Su br ou t in es ❍ In it ia l iz in g Loca l Va r ia bl es Pa ssin g Va l u es t o a Su br ou t in e ❍ Pa ssin g a List t o a Su br ou t in e Ca l l in g Su br ou t in es f r om Ot h er Su br ou t in es Recu r sive Su br ou t in es Pa ssin g Ar r a ys by Na me Usin g Al ia ses Usin g t h e do St a t emen t wit h Su br ou t in es Specif yin g t h e Sor t Or der Pr edef in ed Su br ou t in es ❍ Cr ea t in g St a r t u p Code Usin g BEGIN ❍ Cr ea t in g Ter min a t ion Code Usin g END ❍ Ha n dl in g Non -Exist en t Su br ou t in es Usin g AUTOLOAD Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 10 Associative Arrays ● ● ●

Limit a t ion s of Ar r a y Va r ia bl es Def in it ion Ref er r in g t o Associa t ive Ar r a y El emen t s

● ● ● ● ● ● ●

● ● ●

Addin g El emen t s t o a n Associa t ive Ar r a y Cr ea t in g Associa t ive Ar r a ys Copyin g Associa t ive Ar r a ys f r om Ar r a y Va r ia bl es Addin g a n d Del et in g Ar r a y El emen t s List in g Ar r a y In dexes a n d Va l u es Loopin g Usin g a n Associa t ive Ar r a y Cr ea t in g Da t a St r u ct u r es Usin g Associa t ive Ar r a ys ❍ Lin ked List s ❍ St r u ct u r es ❍ Tr ees ❍ Da t a ba ses ❍ Exa mpl e: A Ca l cu l a t or Pr ogr a m Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 11 Formatting Your Output ● ● ●









● ● ● ●

Def in in g a Pr in t For ma t Displ a yin g a Pr in t For ma t Displ a yin g Va l u es in a Pr in t For ma t ❍ Cr ea t in g a Gen er a l -Pu r pose Pr in t For ma t ❍ Ch oosin g a Va l u e-Fiel d For ma t ❍ Pr in t in g Va l u e-Fiel d Ch a r a ct er s ❍ Usin g t h e Mu l t il in e Fiel d For ma t Wr it in g t o Ot h er Ou t pu t Fil es ❍ Sa vin g t h e Def a u l t Fil e Va r ia bl e Specif yin g a Pa ge Hea der ❍ Ch a n gin g t h e Hea der Pr in t For ma t Set t in g t h e Pa ge Len gt h ❍ Usin g print wit h Pa gin a t ion For ma t t in g Lon g Ch a r a ct er St r in gs ❍ El imin a t in g Bl a n k Lin es Wh en For ma t t in g ❍ Su ppl yin g a n In def in it e Nu mber of Lin es For ma t t in g Ou t pu t Usin g printf Su mma r y Q&A Wor ksh op ❍ Qu iz



Exer cises

Day 12 Working with the File System ●







● ● ●

Fil e In pu t a n d Ou t pu t Fu n ct ion s ❍ Ba sic In pu t a n d Ou t pu t Fu n ct ion s ❍ Skippin g a n d Rer ea din g Da t a ❍ Syst em Rea d a n d Wr it e Fu n ct ion s ❍ Rea din g Ch a r a ct er s Usin g getc ❍ Rea din g a Bin a r y Fil e Usin g binmode Dir ect or y-Ma n ipu l a t ion Fu n ct ion s ❍ Th e mkdir Fu n ct ion ❍ Th e chdir Fu n ct ion ❍ Th e opendir Fu n ct ion ❍ Th e closedir Fu n ct ion ❍ Th e readdir Fu n ct ion ❍ Th e telldir a n d seekdir Fu n ct ion s ❍ Th e rewinddir Fu n ct ion ❍ Th e rmdir Fu n ct ion Fil e-At t r ibu t e Fu n ct ion s ❍ Fil e-Rel oca t ion Fu n ct ion s ❍ Lin k a n d Symbol ic Lin k Fu n ct ion s ❍ Fil e-Per mission Fu n ct ion s ❍ Miscel l a n eou s At t r ibu t e Fu n ct ion s Usin g DBM Fil es ❍ Th e dbmopen Fu n ct ion ❍ Th e dbmclose Fu n ct ion Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 13 Process, String, and Mathematical Functions ●



Pr ocess- a n d Pr ogr a m-Ma n ipu l a t ion Fu n ct ion s ❍ St a r t in g a Pr ocess ❍ Ter min a t in g a Pr ogr a m or Pr ocess ❍ Execu t ion Con t r ol Fu n ct ion s ❍ Miscel l a n eou s Con t r ol Fu n ct ion s Ma t h ema t ica l Fu n ct ion s

Th e sin a n d cos Fu n ct ion s ❍ Th e atan2 Fu n ct ion ❍ Th e sqrt Fu n ct ion ❍ Th e exp Fu n ct ion ❍ Th e log Fu n ct ion ❍ Th e abs Fu n ct ion ❍ Th e rand a n d srand Fu n ct ion s St r in g-Ma n ipu l a t ion Fu n ct ion s ❍ Th e index Fu n ct ion ❍ Th e rindex Fu n ct ion ❍ Th e length Fu n ct ion ❍ Ret r ievin g St r in g Len gt h Usin g tr ❍ Th e pos Fu n ct ion ❍ Th e substr Fu n ct ion ❍ Th e study Fu n ct ion ❍ Ca se Con ver sion Fu n ct ion s ❍ Th e quotemeta Fu n ct ion ❍ Th e join Fu n ct ion ❍ Th e sprintf Fu n ct ion Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍



● ● ●

Day 14 Scalar-Conversion and List-Manipulation Functions ● ● ● ● ● ●

Th e Th e Th e Th e Th e Th e

chop Fu n ct ion chomp Fu n ct ion crypt Fu n ct ion hex Fu n ct ion int Fu n ct ion oct Fu n ct ion

Th e oct Fu n ct ion a n d Hexa decima l In t eger s Th e ord a n d chr Fu n ct ion s Th e scalar Fu n ct ion Th e pack Fu n ct ion ❍ Th e pack Fu n ct ion a n d C Da t a Types Th e unpack Fu n ct ion ❍ Un pa ckin g St r in gs ❍ Skippin g Ch a r a ct er s Wh en Un pa ckin g ❍

● ● ●



Th e unpack Fu n ct ion a n d uuencode Th e vec Fu n ct ion Th e defined Fu n ct ion Th e undef Fu n ct ion Ar r a y a n d List Fu n ct ion s ❍ Th e grep Fu n ct ion ❍ Th e splice Fu n ct ion ❍ Th e shift Fu n ct ion ❍ Th e unshift Fu n ct ion ❍ Th e push Fu n ct ion ❍ Th e pop Fu n ct ion ❍ Cr ea t in g St a cks a n d Qu eu es ❍ Th e split Fu n ct ion ❍ Th e sort a n d reverse Fu n ct ion s ❍ Th e map Fu n ct ion ❍ Th e wantarray Fu n ct ion Associa t ive Ar r a y Fu n ct ion s ❍ Th e keys Fu n ct ion ❍ Th e values Fu n ct ion ❍ Th e each Fu n ct ion ❍ Th e delete Fu n ct ion ❍ Th e exists Fu n ct ion Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍

● ● ● ●



● ● ●

Week 2 Week 2 in Review Week 3 Week 3 at a Glance ●

Wh er e You 'r e Goin g

Day 15 System Functions ●

Syst em Libr a r y Emu l a t ion Fu n ct ion s ❍ Th e getgrent Fu n ct ion ❍ Th e setgrent a n d endgrent Fu n ct ion s ❍ Th e getgrnam Fu n ct ion

Th e getgrid Fu n ct ion ❍ Th e getnetent Fu n ct ion ❍ Th e getnetbyaddr Fu n ct ion ❍ Th e getnetbyname Fu n ct ion ❍ Th e setnetent a n d endnetent Fu n ct ion s ❍ Th e gethostbyaddr Fu n ct ion ❍ Th e gethostbyname Fu n ct ion ❍ Th e gethostent, sethostent, a n d endhostent Fu n ct ion s ❍ Th e getlogin Fu n ct ion ❍ Th e getpgrp a n d setpgrp Fu n ct ion s ❍ Th e getppid Fu n ct ion ❍ Th e getpwnam Fu n ct ion ❍ Th e getpwuid Fu n ct ion ❍ Th e getpwent Fu n ct ion ❍ Th e setpwent a n d endpwent Fu n ct ion s ❍ Th e getpriority a n d setpriority Fu n ct ion s ❍ Th e getprotoent Fu n ct ion ❍ Th e getprotobyname a n d getprotobynumber Fu n ct ion s ❍ Th e setprotoent a n d endprotoent Fu n ct ion s ❍ Th e getservent Fu n ct ion ❍ Th e getservbyname a n d getservbyport Fu n ct ion s ❍ Th e setservent a n d endservent Fu n ct ion s ❍ Th e chroot Fu n ct ion ❍ Th e ioctl Fu n ct ion ❍ Th e alarm Fu n ct ion ❍ Ca l l in g t h e Syst em select Fu n ct ion ❍ Th e dump Fu n ct ion Socket -Ma n ipu l a t ion Fu n ct ion s ❍ Th e socket Fu n ct ion ❍ Th e bind Fu n ct ion ❍ Th e listen Fu n ct ion ❍ Th e accept Fu n ct ion ❍ Th e connect Fu n ct ion ❍ Th e shutdown Fu n ct ion ❍ Th e socketpair Fu n ct ion ❍ Th e getsockopt a n d setsockopt Fu n ct ion s ❍ Th e getsockname a n d getpeername Fu n ct ion s Th e UNIX Syst em V IPC Fu n ct ion s ❍ IPC Fu n ct ion s a n d t h e require St a t emen t ❍ Th e msgget Fu n ct ion ❍ Th e msgsnd Fu n ct ion ❍





Th e msgrcv Fu n ct ion ❍ Th e msgctl Fu n ct ion ❍ Th e shmget Fu n ct ion ❍ Th e shmwrite Fu n ct ion ❍ Th e shmread Fu n ct ion ❍ Th e shmctl Fu n ct ion ❍ Th e semget Fu n ct ion ❍ Th e semop Fu n ct ion ❍ Th e semctl Fu n ct ion Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍

● ● ●

Day 16 Command-Line Options ●

● ● ●

● ●



● ● ● ●

● ● ● ● ●

Specif yin g Opt ion s ❍ Specif yin g Opt ion s on t h e Comma n d Lin e ❍ Specif yin g a n Opt ion in t h e Pr ogr a m Th e -v Opt ion : Pr in t in g t h e Per l Ver sion Nu mber Th e -c Opt ion : Ch eckin g You r Syn t a x Th e -w Opt ion : Pr in t in g Wa r n in gs ❍ Ch eckin g f or Possibl e Typos ❍ Ch eckin g f or Redef in ed Su br ou t in es ❍ Ch eckin g f or In cor r ect Compa r ison Oper a t or s Th e -e Opt ion : Execu t in g a Sin gl e-Lin e Pr ogr a m Th e -s Opt ion : Su ppl yin g You r Own Comma n d-Lin e Opt ion s ❍ Th e -s Opt ion a n d Ot h er Comma n d-Lin e Ar gu men t s Th e -P Opt ion : Usin g t h e C Pr epr ocessor ❍ Th e C Pr epr ocessor : A Qu ick Over view Th e -I Opt ion : Sea r ch in g f or C In cl u de Fil es Th e -n Opt ion : Oper a t in g on Mu l t ipl e Fil es Th e -p Opt ion : Oper a t in g on Fil es a n d Pr in t in g Th e -i Opt ion : Edit in g Fil es ❍ Ba ckin g Up In pu t Fil es Usin g t h e -i Opt ion Th e -a Opt ion : Spl it t in g Lin es Th e -F Opt ion : Specif yin g t h e Spl it Pa t t er n Th e -0 Opt ion : Specif yin g In pu t En d-of -Lin e Th e -l Opt ion : Specif yin g Ou t pu t En d-of -Lin e Th e -x Opt ion : Ext r a ct in g a Pr ogr a m f r om a Messa ge



● ● ● ●

Miscel l a n eou s Opt ion s ❍ Th e -u Opt ion ❍ Th e -U Opt ion ❍ Th e -S Opt ion ❍ Th e -D Opt ion ❍ Th e -T Opt ion : Wr it in g Secu r e Pr ogr a ms Th e -d Opt ion : Usin g t h e Per l Debu gger Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 17 System Variables ●

Gl oba l Sca l a r Va r ia bl es ❍ Th e Def a u l t Sca l a r Va r ia bl e: $_ ❍ Th e Pr ogr a m Na me: $0 ❍ Th e User ID: $< a n d $> ❍ Th e Gr ou p ID: $( a n d $) ❍ Th e Ver sion Nu mber : $] ❍ Th e In pu t Lin e Sepa r a t or : $/ ❍ Th e Ou t pu t Lin e Sepa r a t or : $ ❍ Th e Ou t pu t Fiel d Sepa r a t or : $, ❍ Th e Ar r a y El emen t Sepa r a t or : $" ❍ Th e Nu mber Ou t pu t For ma t : $# ❍ Th e eval Er r or Messa ge: $@ ❍ Th e Syst em Er r or Code: $? ❍ Th e Syst em Er r or Messa ge: $! ❍ Th e Cu r r en t Lin e Nu mber : $. ❍ Mu l t il in e Ma t ch in g: $* ❍ Th e Fir st Ar r a y Su bscr ipt : $[ ❍ Mu l t idimen sion a l Associa t ive Ar r a ys a n d t h e $; Va r ia bl e ❍ Th e Wor d-Br ea k Specif ier : $: ❍ Th e Per l Pr ocess ID: $$ ❍ Th e Cu r r en t Fil en a me: $ARGV ❍ Th e Wr it e Accu mu l a t or : $^A ❍ Th e In t er n a l Debu ggin g Va l u e: $^D ❍ Th e Syst em Fil e Fl a g: $^F ❍ Con t r ol l in g Fil e Edit in g Usin g $^I ❍ Th e For ma t For m-Feed Ch a r a ct er : $^L

Con t r ol l in g Debu ggin g: $^P ❍ Th e Pr ogr a m St a r t Time: $^T ❍ Su ppr essin g Wa r n in g Messa ges: $^W ❍ Th e $^X Va r ia bl e Pa t t er n Syst em Va r ia bl es ❍ Ret r ievin g Ma t ch ed Su bpa t t er n s ❍ Ret r ievin g t h e En t ir e Pa t t er n : $& ❍ Ret r ievin g t h e Un ma t ch ed Text : t h e $` a n d $' Va r ia bl es ❍ Th e $+ Va r ia bl e Fil e Syst em Va r ia bl es ❍ Th e Def a u l t Pr in t For ma t : $~ ❍ Specif yin g Pa ge Len gt h : $= ❍ Lin es Rema in in g on t h e Pa ge: $❍ Th e Pa ge Hea der Pr in t For ma t : $^ ❍ Bu f f er in g Ou t pu t : $| ❍ Th e Cu r r en t Pa ge Nu mber : $% Ar r a y Syst em Va r ia bl es ❍ Th e @_ Va r ia bl e ❍ Th e @ARGV Va r ia bl e ❍ Th e @F Va r ia bl e ❍ Th e @INC Va r ia bl e ❍ Th e %INC Va r ia bl e ❍ Th e %ENV Va r ia bl e ❍ Th e %SIG Va r ia bl e Bu il t -In Fil e Va r ia bl es ❍ STDIN, STDOUT, a n d STDERR ❍











ARGV



DATA

Th e Un der scor e Fil e Va r ia bl e Specif yin g Syst em Va r ia bl e Na mes a s Wor ds Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises ❍

● ● ● ●

Day 18 References in Perl 5 ● ● ●

In t r odu ct ion t o Ref er en ces Usin g Ref er en ces Usin g t h e Ba cksl a sh Oper a t or

● ● ●







● ● ● ● ●



Ref er en ces a n d Ar r a ys Mu l t idimen sion a l Ar r a ys Ref er en ces t o Su br ou t in es ❍ Usin g Su br ou t in e Templ a t es Usin g Su br ou t in es t o Wor k wit h Mu l t ipl e Ar r a ys ❍ Pa ss By Va l u e or By Ref er en ce? Ref er en ces t o Fil e Ha n dl es ❍ Wh a t Does t h e *variable Oper a t or Do? Usin g Symbol ic Ref er en ces… Aga in ❍ Decl a r in g Va r ia bl es wit h Cu r l y Br a ces Mor e on Ha r d Ver su s Symbol ic Ref er en ces For Mor e In f or ma t ion Su mma r y Q&A Wor ksh op ❍ Qu iz Exer cises

Day 19 Object-Oriented Programming in Perl ●

● ● ●

● ● ● ● ● ● ● ● ● ● ●

An In t r odu ct ion t o Modu l es ❍ Th e Th r ee Impor t a n t Ru l es Cl a sses in Per l Cr ea t in g a Cl a ss Bl essin g a Con st r u ct or ❍ In st a n ce Va r ia bl es Met h ods Expor t in g Met h ods In vokin g Met h ods Over r ides Dest r u ct or s In h er it a n ce Over r idin g Met h ods A Few Commen t s Abou t Cl a sses a n d Object s in Per l Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Day 20 Miscellaneous Features of Perl







● ● ●



● ●



● ● ● ● ● ●

Th e require Fu n ct ion ❍ Th e require Fu n ct ion a n d Su br ou t in e Libr a r ies ❍ Usin g require t o Specif y a Per l Ver sion Th e $#array Va r ia bl es ❍ Con t r ol l in g Ar r a y Len gt h Usin g $#array Al t er n a t ive St r in g Del imit er s ❍ Def in in g St r in gs Usin g Comma n ds ❍ Displ a yin g Lin e Act ion s Usin g t h e L Comma n d Ot h er Debu ggin g Comma n ds ❍ Execu t in g Ot h er Per l St a t emen t s ❍ Th e H Comma n d: List in g Pr ecedin g Comma n ds ❍ Th e ! Comma n d: Execu t in g Pr eviou s Comma n ds ❍ Th e T Comma n d: St a ck Tr a cin g ❍ Th e p Comma n d: Pr in t in g a n Expr ession ❍ Th e = Comma n d: Def in in g Al ia ses ❍ Pr edef in in g Al ia ses ❍ Th e h Comma n d: Debu gger Hel p Su mma r y Q&A Wor ksh op



Qu iz

Week 3 Week 3 in Review Appendix A Answers ●























An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz

1, "Get t in g St a r t ed"

2, "Ba sic Oper a t or s a n d Con t r ol Fl ow"

3, "Un der st a n din g Sca l a r Va l u es"

4, "Mor e Oper a t or s"

5, "List s a n d Ar r a y Va r ia bl es"

6, "Rea din g f r om a n d Wr it in g t o Fil es"

7, "Pa t t er n Ma t ch in g"

8, "Mor e Con t r ol St r u ct u r es"

9, "Usin g Su br ou t in es"

10, "Associa t ive Ar r a ys"

11, "For ma t t in g You r Ou t pu t "

12, "Wor kin g wit h t h e Fil e Syst em"

Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y Per l 5" ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍ Exer cises An swer s f or Da y ❍ Qu iz ❍



















13, "Pr ocess, St r in g, a n d Ma t h ema t ica l Fu n ct ion s"

14, "Sca l a r -Con ver sion a n d List -Ma n ipu l a t ion Fu n ct ion s"

15, "Syst em Fu n ct ion s"

16, "Comma n d-Lin e Opt ion s"

17, "Syst em Va r ia bl es"

18, "Ref er en ces in

19, "Object -Or ien t ed Pr ogr a mmin g in Per l "

20, "Miscel l a n eou s Fea t u r es of Per l "

21, "Th e Per l Debu gger "

Appendix B ASCII Character Set

Credits

Co pyr ig ht © 1996 by Sa ms Pu bl ish in g SECOND EDITION Al l r igh t s r eser ved. No pa r t of t h is book sh a l l be r epr odu ced, st or ed in a r et r ieva l

syst em, or t r a n smit t ed by a n y mea n s, el ect r on ic, mech a n ica l , ph ot ocopyin g, r ecor din g, or ot h er wise, wit h ou t wr it t en per mission f r om t h e pu bl ish er . No pa t en t l ia bil it y is a ssu med wit h r espect t o t h e u se of t h e in f or ma t ion con t a in ed h er ein . Al t h ou gh ever y pr eca u t ion h a s been t a ken in t h e pr epa r a t ion of t h is book, t h e pu bl ish er a n d a u t h or a ssu me n o r espon sibil it y f or er r or s or omission s. Neit h er is a n y l ia bil it y a ssu med f or da ma ges r esu l t in g f r om t h e u se of t h e in f or ma t ion con t a in ed h er ein . For in f or ma t ion , a ddr ess Sa ms Pu bl ish in g, 201 W. 103r d St ., In dia n a pol is, IN 46290. Int e r nat io nal St andar d Bo o k Numbe r : 0-672-30894-0 HTML c o nve r sio n by : M/s. Lea f Wr it er s (In dia ) Pvt . Lt d. Website : h t t p://l ea f .st pn .sof t .n et e-mail : l ea f wr it er s@l ea f .st pn .sof t .n et

Richard K. Swadley Publ ishe r and Pr e side nt Dean Miller De ve l o pme nt Manag e r Mar ke t ing Manag e r John Pierce Ac quisit io ns Edit o r Chris Denny So f t war e De ve l o pme nt Spe c ial ist Co py Edit o r Edit o r ial Co o r dinat o r Fo r mat t e r

Steve Straiger

Co ve r De sig ne r Co py Wr it e r

Tim Amrhein Peter Fuller

Pr o duc t io n

Acknowledgments

Kimberly K. Hannel Bill Whitmer Frank Sinclair

Ac quisit io ns Manag e r Manag ing Edit o r

Greg Wiegand

Assist ant Mar ke t ing Manag e r De ve l o pme nt Edit o r s Pr o duc t io n Edit o r

Kristina Perry

Te c hnic al Re vie we r Te c hnic al Edit Co o r dinat o r Edit o r ial Assist ant s

Elliotte Rusty Harold Lynette Quinn

Cindy Morrow

Angelique Brittingham, Keith Davenport Tonya R. Simpson

Carol Ackerman, Andi Richter Rhonda, TinchMize Gary Adair Brad Chinn

Bo o k De sig ne r Pr o duc t io n Te am Supe r viso r Michael Brumitt, Charlotte Clapp, Jason Hand, Sonja Hart, Louisa Klucznik, Ayanna Lacey, Clint Lahnen, Paula Lowell, Laura Robbins, Bobbi Satterfield, Carol Sheehan, Chris Wilcox

I wou l d l ike t o t h a n k t h e f ol l owin g peopl e f or t h eir h el p: ●

● ●

Da vid Ma ckl em a t Siet ec Open Syst ems f or a l l owin g me t o t a ke t h e t ime of f t o wor k on t h e f ir st edit ion of t h is book Ever yon e a t Sa ms Pu bl ish in g, f or t h eir ef f or t s a n d en cou r a gemen t Jim Ga r dn er , f or t el l in g t h e peopl e a t Sa ms Pu bl ish in g a bou t me

I'd a l so l ike t o t h a n k a l l t h ose f r ien ds of min e (you kn ow wh o you a r e) wh o t ol er a t ed my goin g st ir -cr a z y a s my dea dl in es a ppr oa ch ed.

About the Authors David Till Da vid Til l is a t ech n ica l wr it er wor kin g in Tor on t o, On t a r io, Ca n a da . He h ol ds a ma st er 's degr ee in compu t er scien ce f r om t h e Un iver sit y of Wa t er l oo; pr ogr a mmin g l a n gu a ges wa s h is ma jor f iel d of st u dy. He a l so h a s wor ked in compil er devel opmen t a n d on ver sion -con t r ol sof t wa r e. He l ist s h is h obbies a s "wr it in g, comedy, wa l kin g, du pl ica t e br idge, a n d f a n a t ica l su ppor t of t h e Tor on t o Bl u e Ja ys." He ca n be r ea ch ed via e-ma il a t [email protected] or [email protected], or on t h e Wor l d Wide Web a t http://www.interlog.com/~davet/. Kamran Husain Ka mr a n Hu sa in is a sof t wa r e con su l t a n t wit h exper ien ce in UNIX syst em pr ogr a mmin g. He h a s da bbl ed in a l l sor t s of sof t wa r e f or r ea l -t ime syst ems a ppl ica t ion s, t el ecommu n ica t ion s, seismic da t a a cqu isit ion a n d n a viga t ion , X Win dow/Mot if a n d Micr osof t Win dows a ppl ica t ion s. He r ef u ses t o divu l ge a n y mor e of h is qu a l if ica t ion s. Ka mr a n of f er s con su l t in g ser vices a n d t r a in in g cl a sses t h r ou gh h is compa n y, MPS In c., in Hou st on , Texa s. He is a n a l u mn u s of t h e Un iver sit y of Texa s a t Au st in . You ca n r ea ch Ka mr a n t h r ou gh Sa ms Pu bl ish in g or via e-ma il a t [email protected] or [email protected].

Introduction Th is book is design ed t o t ea ch you t h e Per l pr ogr a mmin g l a n gu a ge in ju st 21 da ys. Wh en you f in ish r ea din g t h is book, you wil l h a ve l ea r n ed wh y Per l is gr owin g r a pidl y in popu l a r it y: It is power f u l en ou gh t o per f or m ma n y u sef u l , soph ist ica t ed pr ogr a mmin g t a sks, yet it is ea sy t o l ea r n a n d u se.

Who Should Read This Book? No pr eviou s pr ogr a mmin g exper ien ce is r equ ir ed f or you t o l ea r n ever yt h in g you n eed t o kn ow a bou t pr ogr a mmin g wit h Per l f r om t h is book. In pa r t icu l a r , n o kn owl edge of t h e C pr ogr a mmin g l a n gu a ge is r equ ir ed. If you a r e f a mil ia r wit h ot h er pr ogr a mmin g l a n gu a ges, l ea r n in g Per l wil l be a sn a p. Th e on l y a ssu mpt ion t h is book does ma ke is t h a t you a r e f a mil ia r wit h t h e ba sics of u sin g t h e UNIX oper a t in g syst em.

Special Features of This Book Th is book con t a in s some specia l el emen t s t h a t h el p you u n der st a n d Per l f ea t u r es a n d con cept s a s t h ey a r e in t r odu ced: ● ● ● ● ●

Syn t a x boxes DO/DON'T boxes Not es Wa r n in gs Tips

Syntax boxes expl a in some of t h e mor e compl ica t ed f ea t u r es of Per l , su ch a s t h e con t r ol st r u ct u r es. Ea ch syn t a x box con sist s of a f or ma l def in it ion of t h e f ea t u r e f ol l owed by a n expl a n a t ion of t h e el emen t s of t h e f ea t u r e. Her e is a n exa mpl e of a syn t a x box: Th e syn t a x of t h e for st a t emen t is

for (expr1; expr2; expr3) { statement_block }

expr1 is t h e l oop in it ia l iz er . It is eva l u a t ed on l y on ce, bef or e t h e st a r t of t h e l oop. expr2 is t h e con dit ion a l expr ession t h a t t er min a t es t h e l oop. Th e con dit ion a l expr ession in expr2 beh a ves ju st l ike t h e on es in while a n d if st a t emen t s: If it s va l u e is z er o, t h e

l oop is t er min a t ed, a n d if it s va l u e is n on z er o, t h e l oop is execu t ed. statement_block is t h e col l ect ion of st a t emen t s t h a t is execu t ed if (a n d wh en ) expr2 h a s

a n on z er o va l u e. expr3 is execu t ed on ce per it er a t ion of t h e l oop, a n d is execu t ed a f t er t h e l a st st a t emen t in statement_block is execu t ed.

Don 't t r y t o u n der st a n d t h is def in it ion yet ! DO/DON'T boxes pr esen t t h e do's a n d don 't s f or a pa r t icu l a r t a sk or f ea t u r e. Her e is a n exa mpl e of su ch a box:

DON'T con f u se t h e | oper a t or (bit wise OR) wit h t h e || oper a t or (l ogica l OR). DO ma ke su r e you a r e u sin g t h e pr oper bit wise oper a t or . It 's ea sy t o sl ip a n d a ssu me you wa n t bit wise OR wh en you r ea l l y wa n t bit wise AND. (Tr u st me.

Notes a r e expl a n a t ion s of in t er est in g pr oper t ies of a pa r t icu l a r pr ogr a m f ea t u r e. Her e is a n exa mpl e of a n ot e: NOTE In l ef t -ju st if ied ou t pu t , t h e va l u e bein g displ a yed a ppea r s a t t h e l ef t en d of t h e va l u e f iel d. In r igh t ju st if ied ou t pu t , t h e va l u e bein g displ a yed a ppea r s a t t h e r igh t en d of t h e va l u e f iel d.

Warnings wa r n you of pr ogr a mmin g pit f a l l s t o a void. Her e is a t ypica l wa r n in g:

You ca n n ot u se t h e last st a t emen t in side t h e do st a t emen t . Th e do st a t emen t , a l t h ou gh it beh a ves l ike t h e ot h er con t r ol st r u ct u r es, is a ct u a l l y impl emen t ed dif f er en t l y.

Tips a r e h in t s on h ow t o wr it e you r Per l pr ogr a ms bet t er . Her e is a n exa mpl e of a t ip: TIP

It is a good idea t o u se a l l u pper ca se l et t er s f or you r f il e va r ia bl e n a mes. Th is ma kes it ea sier t o dist in gu ish f il e va r ia bl e n a mes f r om ot h er va r ia bl e n a mes a n d f r om r eser ved wor ds.

Programming Examples Ea ch f ea t u r e of Per l is il l u st r a t ed by exa mpl es of it s u se. In a ddit ion , ea ch ch a pt er of t h is book con t a in s ma n y u sef u l pr ogr a mmin g exa mpl es compl et e wit h expl a n a t ion s; t h ese exa mpl es sh ow you h ow you ca n u se Per l f ea t u r es in you r own pr ogr a ms. Ea ch exa mpl e con t a in s a l ist in g of t h e pr ogr a m, t h e in pu t r equ ir ed by a n d t h e ou t pu t gen er a t ed by t h e pr ogr a m, a n d a n a n a l ysis of h ow t h e pr ogr a m wor ks. Specia l icon s a r e u sed t o poin t ou t ea ch pa r t of t h e exa mpl e: Type, In pu t -Ou t pu t , a n d An a l ysis. In t h e In pu t -Ou t pu t exa mpl e f ol l owin g List in g IN.1, t h er e a r e some specia l t ypogr a ph ic con ven t ion s. Th e in pu t you en t er is sh own in bold monospace t ype, a n d t h e ou t pu t gen er a t ed by t h e syst em or t h e pr ogr a m is sh own in plain monospace t ype. Th e syst em pr ompt ($ in t h e exa mpl es in t h is book) is sh own so t h a t you kn ow wh en a comma n d is t o be en t er ed on t h e comma n d l in e.

List ing IN.1. A simpl e Pe r l pr o g r am wit h c o mme nt s. 1: #!/usr/local/bin/perl 2: # this program reads a line of input, and writes the line 3: # back out 4: $inputline = ;

# read a line of input

5: print( $inputline );

# write the line out

$ programIN_1 This is a line of input. This is a line of input. $

Lin e 1 is t h e h ea der commen t . Lin es 2 a n d 3 a r e commen t s, n ot execu t a bl e l in es of code. Lin e 4 r ea ds a l in e of in pu t . Lin e 5 wr it es t h e l in e of in pu t on you r scr een .

End-of-Day Q& A and Workshop Ea ch da y en ds wit h a Q&A sect ion con t a in in g a n swer s t o common qu est ion s r el a t in g t o t h a t da y's ma t er ia l . Th er e a l so is a Wor ksh op a t t h e en d of ea ch da y t h a t con sist s of qu iz qu est ion s a n d pr ogr a mmin g exer cises. Th e exer cises of t en in cl u de BUG BUSTER exer cises t h a t h el p you spot some of t h e common bu gs t h a t cr op u p in Per l pr ogr a ms. Th e a n swer s t o t h ese qu iz qu est ion s a s wel l a s sa mpl e sol u t ion s f or t h e exer cises a r e pr esen t ed in Appen dix A, "An swer s."

Conventions Used in This Book Th is book u ses dif f er en t t ypef a ces t o h el p you dif f er en t ia t e bet ween Per l code a n d r egu l a r En gl ish , a n d a l so t o h el p you iden t if y impor t a n t con cept s. ●







Act u a l Per l code is t ypeset in a specia l monospace f on t . You 'l l see t h is f on t u sed in l ist in gs a n d t h e In pu t -Ou t pu t exa mpl es, a s wel l a s in code sn ippet s. In t h e expl a n a t ion s of Per l f ea t u r es, comma n ds, f il en a mes, st a t emen t s, va r ia bl es, a n d a n y t ext you see on t h e scr een a l so a r e t ypeset in t h is f on t . Comma n d in pu t a n d a n yt h in g t h a t you a r e su pposed t o en t er a ppea r s in a bold monospace f on t . You 'l l see t h is ma in l y in t h e In pu t -Ou t pu t exa mpl es. Pl a ceh ol der s in syn t a x descr ipt ion s a ppea r in a n italic monospace f on t . Repl a ce t h e pl a ceh ol der wit h t h e a ct u a l f il en a me, pa r a met er , or wh a t ever el emen t it r epr esen t s. Italics h igh l igh t t ech n ica l t er ms wh en t h ey f ir st a ppea r in t h e t ext a n d a r e somet imes u sed t o emph a siz e impor t a n t poin t s.

What You'll Learn in 21 Days In you r f ir st week of l ea r n in g Per l , you 'l l l ea r n en ou gh of t h e ba sics of Per l t o wr it e ma n y u sef u l Per l pr ogr a ms. Her e's a su mma r y of wh a t you 'l l l ea r n in Week 1: Day 1, "Ge t t ing St ar t e d," t el l s you h ow t o get Per l , h ow t o r u n Per l pr ogr a ms, a n d h ow t o r ea d f r om you r keyboa r d a n d wr it e t o you r scr een . Day 2, "Basic Ope r at o r s and Co nt r o l Fl o w," t ea ch es you a bou t simpl e a r it h met ic, h ow t o a ssign a va l u e t o a sca l a r va r ia bl e, a n d h ow t o con t r ol execu t ion u sin g con dit ion a l st a t emen t s.

Day 3, "Unde r st anding Sc al ar Val ue s," t ea ch es you a bou t in t eger s, f l oa t in g-poin t n u mber s, a n d ch a r a ct er st r in gs. It a l so sh ows you t h a t a l l t h r ee a r e in t er ch a n gea bl e in Per l . Day 4, "Mo r e Ope r at o r s," t el l s you a l l a bou t oper a t or s a n d expr ession s in Per l a n d t a l ks a bou t oper a t or a ssocia t ivit y a n d pr eceden ce. Day 5, "List s and Ar r ay Var iabl e s," in t r odu ces you t o l ist s, wh ich a r e col l ect ion s of va l u es, a n d t o a r r a y va r ia bl es, wh ich st or e l ist s. Day 6, "Re ading f r o m and Wr it ing t o Fil e s," t el l s you h ow t o in t er a ct wit h you r f il e syst em by r ea din g f r om in pu t f il es, wr it in g t o ou t pu t f il es, a n d t est in g f or pa r t icu l a r f il e a t t r ibu t es. Day 7, "Pat t e r n Mat c hing ," descr ibes pa t t er n -ma t ch in g in Per l a n d sh ows h ow you ca n su bst it u t e va l u es a n d t r a n sl a t e set s of ch a r a ct er s in t ext st r in gs. By t h e en d of Week 2, you 'l l h a ve ma st er ed a l most a l l t h e f ea t u r es of Per l ; you 'l l a l so h a ve l ea r n ed a bou t ma n y of t h e l ibr a r y f u n ct ion s su ppl ied wit h t h e l a n gu a ge. Her e's a su mma r y of wh a t you 'l l l ea r n : Day 8, "Mo r e Co nt r o l St r uc t ur e s," discu sses t h e con t r ol f l ow st a t emen t s n ot pr eviou sl y cover ed. Day 9, "Using Subr o ut ine s," sh ows h ow you ca n br ea k you r pr ogr a m in t o sma l l er , mor e ma n a gea bl e, ch u n ks. Day 10, "Asso c iat ive Ar r ays," in t r odu ces on e of t h e most power f u l a n d u sef u l con st r u ct s in Per l -a r r a ys-a n d it sh ows h ow you ca n u se t h ese a r r a ys t o simu l a t e ot h er da t a st r u ct u r es. Day 11, "Fo r mat t ing Yo ur Out put ," sh ows h ow you ca n u se Per l t o pr odu ce t idy r epor t s. Day 12, "Wo r king wit h t he Fil e Syst e m," sh ows h ow you ca n in t er a ct wit h you r syst em's dir ect or y st r u ct u r e. Day 13, "Pr o c e ss, St r ing , and Mat he mat ic al Func t io ns," descr ibes t h e l ibr a r y f u n ct ion s t h a t in t er a ct wit h pr ocesses r u n n in g on t h e syst em. It a l so descr ibes t h e f u n ct ion s t h a t per f or m t r igon omet r ic a n d ot h er ma t h ema t ica l oper a t ion s, a n d t h e f u n ct ion s t h a t oper a t e on st r in gs.

Day 14, "Sc al ar -Co nve r sio n and List -Manipul at io n Func t io ns," descr ibes t h e l ibr a r y f u n ct ion s t h a t con ver t va l u es f r om on e f or m t o a n ot h er a n d t h e f u n ct ion s t h a t wor k wit h l ist s a n d a r r a y va r ia bl es. By t h e en d of Week 3, you 'l l kn ow a l l t h e f ea t u r es a n d ca pa bil it ies of Per l . It cover s t h e r est of t h e Per l l ibr a r y f u n ct ion s a n d descr ibes some of t h e mor e esot er ic con cept s of t h e l a n gu a ge. Her e's a su mma r y of wh a t you 'l l l ea r n : Day 15, "Syst e m Func t io ns," descr ibes t h e f u n ct ion s t h a t ma n ipu l a t e t h e Ber kel ey UNIX a n d UNIX Syst em V en vir on men t s. Day 16, "Co mmand-Line Opt io ns," descr ibes t h e opt ion s you ca n su ppl y wit h Per l t o con t r ol h ow you r pr ogr a m r u n s. Day 17, "Syst e m Var iabl e s," descr ibes t h e bu il t -in va r ia bl es t h a t a r e in cl u ded a u t oma t ica l l y a s pa r t of ever y Per l pr ogr a m. Day 18, "Re f e r e nc e s in Pe r l 5," descr ibes t h e poin t er a n d r ef er en ce f ea t u r es of Per l 5, in cl u din g mu l t i-dimen sion a l a r r a ys. Day 19, "Obj e c t -Or ie nt e d Pr o g r amming in Pe r l ," descr ibes t h e object or ien t ed ca pa bil it ies a dded t o Per l 5. Th ese en a bl e you t o h ide in f or ma t ion a n d divide you r pr ogr a m in t o in dividu a l f il e modu l es. Day 20, "Misc e l l ane o us Fe at ur e s o f Pe r l ," cover s some of t h e mor e exot ic or obscu r e f ea t u r es of t h e l a n gu a ge. Day 21, "The Pe r l De bug g e r ," sh ows you h ow t o u se t h e Per l debu gger t o discover er r or s qu ickl y.

We e k 1 Week at a Glance

CONTENTS ●

Wh er e You 'r e Goin g

In you r f ir st week of t ea ch in g you r sel f Per l , you 'l l l ea r n en ou gh of t h e ba sics t o wr it e ma n y u sef u l Per l pr ogr a ms. Al t h ou gh some exper ien ce in u sin g a pr ogr a mmin g l a n gu a ge wil l be a n a dva n t a ge a s you r ea d t h is book, it is n ot r equ ir ed. In pa r t icu l a r , you don 't n eed t o kn ow t h e C pr ogr a mmin g l a n gu a ge bef or e you r ea d t h is book. To u se t h is book ef f ect ivel y, you sh ou l d be a bl e t o t r y ou t some of t h e f ea t u r es of Per l a s you l ea r n t h em. To do t h is, you sh ou l d h a ve Per l r u n n in g on you r syst em. If you don 't h a ve Per l , Da y 1, "Get t in g St a r t ed," t el l s h ow you ca n get it f or f r ee. Ea ch ch a pt er of t h is book con t a in s qu iz a n d exer cise qu est ion s t h a t t est you on t h e ma t er ia l cover ed in t h e da y's l esson . Th ese qu est ion s a r e a n swer ed in Appen dix A, "An swer s."

Where You're Going Th e f ir st week cover s t h e essen t ia l s of Per l . Her e's a su mma r y of wh a t you 'l l l ea r n . Da y 1, "Get t in g St a r t ed," t el l s you h ow t o get Per l , h ow t o r u n Per l pr ogr a ms, a n d h ow t o r ea d in pu t f r om you r keyboa r d a n d wr it e ou t pu t t o you r scr een . Da y 2, "Ba sic Oper a t or s a n d Con t r ol Fl ow," t ea ch es you a bou t simpl e a r it h met ic, h ow t o a ssign a va l u e t o a sca l a r va r ia bl e, a n d h ow t o con t r ol execu t ion u sin g con dit ion a l st a t emen t s. Da y 3, "Un der st a n din g Sca l a r Va l u es," t ea ch es you a bou t in t eger s, f l oa t in g-poin t

n u mber s, a n d ch a r a ct er st r in gs. It a l so sh ows you t h a t a l l t h r ee a r e in t er ch a n gea bl e in Per l . Da y 4, "Mor e Oper a t or s," t el l s you a l l a bou t oper a t or s a n d expr ession s in Per l a n d t a l ks a bou t oper a t or a ssocia t ivit y a n d pr eceden ce. Da y 5, "List s a n d Ar r a y Va r ia bl es," in t r odu ces you t o l ist s, wh ich a r e col l ect ion s of va l u es, a n d t o a r r a y va r ia bl es, wh ich st or e l ist s. Da y 6, "Rea din g f r om a n d Wr it in g t o Fil es," t el l s you h ow t o in t er a ct wit h you r f il e syst em by r ea din g f r om in pu t f il es, wr it in g t o ou t pu t f il es, a n d t est in g f or pa r t icu l a r f il e a t t r ibu t es. Fin a l l y, Da y 7, "Pa t t er n Ma t ch in g," descr ibes pa t t er n ma t ch in g in Per l a n d sh ows h ow you ca n su bst it u t e va l u es a n d t r a n sl a t e set s of ch a r a ct er s in t ext st r in gs. Th is is qu it e a bit of ma t er ia l t o l ea r n in on e week; h owever , by t h e en d of t h e week you 'l l kn ow most of t h e essen t ia l s of Per l a n d wil l be a bl e t o wr it e ma n y u sef u l pr ogr a ms.

Chapter 1 Getting Started

CONTENTS ● ●

● ●







● ● ● ● ●

Wh a t Is Per l ? How Do I Fin d Per l ? ❍ Wh er e Do I Get Per l ? ❍ Ot h er Pl a ces t o Get Per l A Sa mpl e Per l Pr ogr a m Ru n n in g a Per l Pr ogr a m ❍ If Somet h in g Goes Wr on g Th e Fir st Lin e of You r Per l Pr ogr a m: How Commen t s Wor k ❍ Commen t s Lin e 2: St a t emen t s, Token s, a n d ❍ St a t emen t s a n d Token s ❍ Token s a n d Wh it e Spa ce ❍ Wh a t t h e Token s Do: Rea din g f r om St a n da r d In pu t Lin e 3: Wr it in g t o St a n da r d Ou t pu t ❍ Fu n ct ion In voca t ion s a n d Ar gu men t s Er r or Messa ges In t er pr et ive La n gu a ges Ver su s Compil ed La n gu a ges Su mma r y Q&A Wor ksh op ❍ Qu iz ❍ Exer cises

Wel come t o Teach Yourself Perl 5 in 21 Days. Toda y you 'l l l ea r n a bou t t h e f ol l owin g: ● ● ● ● ● ●

Wh a t Per l is a n d wh y Per l is u sef u l How t o get Per l if you do n ot a l r ea dy h a ve it How t o r u n Per l pr ogr a ms How t o wr it e a ver y simpl e Per l pr ogr a m Th e dif f er en ce bet ween in t er pr et ive a n d compil ed pr ogr a mmin g l a n gu a ges Wh a t a n a l gor it h m is a n d h ow t o devel op on e

What Is Perl? Per l is a n a cr on ym, sh or t f or Pr a ct ica l Ext r a ct ion a n d Repor t La n gu a ge. It wa s design ed by La r r y Wa l l a s a t ool f or wr it in g pr ogr a ms in t h e UNIX en vir on men t a n d is con t in u a l l y bein g u pda t ed a n d ma in t a in ed by h im. For it s ma n y f a n s, Per l pr ovides t h e best of sever a l wor l ds. For in st a n ce: ●





Per l h a s t h e power a n d f l exibil it y of a h igh -l evel pr ogr a mmin g l a n gu a ge su ch a s C. In f a ct , a s you wil l see, ma n y of t h e f ea t u r es of t h e l a n gu a ge a r e bor r owed f r om C. Like sh el l scr ipt l a n gu a ges, Per l does n ot r equ ir e a specia l compil er a n d l in ker t o t u r n t h e pr ogr a ms you wr it e in t o wor kin g code. In st ea d, a l l you h a ve t o do is wr it e t h e pr ogr a m a n d t el l Per l t o r u n it . Th is mea n s t h a t Per l is idea l f or pr odu cin g qu ick sol u t ion s t o sma l l pr ogr a mmin g pr obl ems, or f or cr ea t in g pr ot ot ypes t o t est pot en t ia l sol u t ion s t o l a r ger pr obl ems. Per l pr ovides a l l t h e f ea t u r es of t h e scr ipt l a n gu a ges sed a n d a wk, pl u s f ea t u r es n ot f ou n d in eit h er of t h ese t wo l a n gu a ges. Per l a l so su ppor t s a sed-t o-Per l t r a n sl a t or a n d a n a wk-t o-Per l t r a n sl a t or .

In sh or t , Per l is a s power f u l a s C bu t a s con ven ien t a s a wk, sed, a n d sh el l scr ipt s. NOTE Th is book a ssu mes t h a t you a r e f a mil ia r wit h t h e ba sics of u sin g t h e UNIX oper a t in g syst em

As you 'l l see, Per l is ver y ea sy t o l ea r n . In deed, if you a r e f a mil ia r wit h ot h er pr ogr a mmin g l a n gu a ges, l ea r n in g Per l is a sn a p. Even if you h a ve ver y l it t l e pr ogr a mmin g exper ien ce, Per l ca n h a ve you wr it in g u sef u l pr ogr a ms in a ver y sh or t t ime. By t h e en d of Da y 2, "Ba sic Oper a t or s a n d Con t r ol Fl ow," you 'l l kn ow en ou gh a bou t Per l t o be a bl e t o sol ve ma n y pr obl ems.

How Do I Find Perl? To f in d ou t wh et h er Per l a l r ea dy is a va il a bl e on you r syst em, do t h e f ol l owin g: ●



If you a r e cu r r en t l y wor kin g in a UNIX pr ogr a mmin g en vir on men t , ch eck t o see wh et h er t h e f il e /usr/local/bin/perl exist s. If you a r e wor kin g in a n y ot h er en vir on men t , ch eck t h e pl a ce wh er e you n or ma l l y keep you r execu t a bl e pr ogr a ms, or ch eck t h e dir ect or ies a ccessibl e f r om you r PATH en vir on men t va r ia bl e.

If you do n ot f in d Per l in t h is wa y, t a l k t o you r syst em a dmin ist r a t or a n d a sk wh et h er sh e or h e h a s Per l r u n n in g somewh er e el se. If you don 't h a ve Per l r u n n in g in you r en vir on men t , don 't despa ir -r ea d on !

Where Do I Get Perl? On e of t h e r ea son s Per l is becomin g so popu l a r is t h a t it is a va il a bl e f r ee of ch a r ge t o a n yon e wh o wa n t s it . If you a r e on t h e In t er n et , you ca n obt a in a copy of Per l wit h f il et r a n sf er pr ot ocol (FTP). Th e f ol l owin g is a sa mpl e FTP session t h a t t r a n sf er s a copy of t h e Per l dist r ibu t ion . Th e it ems sh own in bol df a ce t ype a r e wh a t you wou l d en t er du r in g t h e session . $ ftp prep.ai.mit.edu Connected to prep.ai.mit.edu. 220 aeneas FTP server (Version wu-2.4(1) Thu Apr 14 20:21:35 EDT 1994) ready. Name (prep.ai.mit.edu:dave): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: 230-Welcome, archive user! 230230-If you have problems downloading and are seeing "Access denied" or 230-"Permission denied", please make sure that you started your FTP 230-client in a directory to which you have write permission. 230230-If you have any problems with the GNU software or its downloading, 230-please refer your questions to . If you have any 230-other unusual problems, please report them to . 230230-If you do have problems, please try using a dash (-) as the first 230-character of your password - this will turn off the continuation 230-messages that may be confusing your FTP client.

230230 Guest login ok, access restrictions apply. ftp> cd pub/gnu 250-If you have problems downloading and are seeing "Access denied" or 250-"Permission denied", please make sure that you started your FTP 250-client in a directory to which you have write permission. 250250-Please note that all files ending in '.gz' are compressed with 250-'gzip', not with the unix 'compress' program.

Get the file README

250- and read it for more information. 250250-Please read the file README 250-

it was last modified on Thu Feb 1 15:00:50 1996 - 32 days ago

250-Please read the file README-about-.diff-files 250-

it was last modified on Fri Feb 2 12:57:14 1996 - 31 days ago

250-Please read the file README-about-.gz-files 250-

it was last modified on Wed Jun 14 16:59:43 1995 - 264 days ago

250 CWD command successful. ftp> binary 200 Type set to I. ftp> get perl-5.001.tar.gz 200 PORT command successful. 150 Opening ASCII mode data connection for perl-5.001.tar.gz (1130765 bytes). 226 Transfer complete. 1130765 bytes received in 9454 seconds (1.20 Kbytes/s) ftp> quit 221 Goodbye. $

Th e comma n ds en t er ed in t h is session a r e expl a in ed in t h e f ol l owin g st eps. If some of t h ese st eps a r e n ot f a mil ia r t o you , a sk you r syst em a dmin ist r a t or f or h el p. 1. Th e comma n d $ ftp prep.ai.mit.edu

2. 3.

4. 5. 6.

7.

con n ect s you t o t h e ma in Fr ee Sof t wa r e Fou n da t ion sou r ce deposit or y a t MIT. Th e u ser ID anonymous t el l s FTP t h a t you wa n t t o per f or m a n a n on ymou s FTP oper a t ion . Wh en FTP a sks f or a pa sswor d, en t er you r u ser ID a n d n et wor k a ddr ess. Th is l et s t h e MIT syst em a dmin ist r a t or kn ow wh o is u sin g t h e MIT a r ch ives. (For secu r it y r ea son s, t h e pa sswor d is n ot a ct u a l l y displ a yed wh en you t ype it .) Th e comma n d cd pub/gnu set s you r cu r r en t wor kin g dir ect or y t o be t h e dir ect or y con t a in in g t h e Per l sou r ce. Th e binary comma n d t el l s FTP t h a t t h e f il e you 'l l be r eceivin g is a f il e t h a t con t a in s u n r ea da bl e (n on -t ext ) ch a r a ct er s. Th e get comma n d copies t h e f il e perl-5.001.tar.gz f r om t h e MIT sou r ce deposit or y t o you r own sit e. (It 's u su a l l y best t o do t h is in of f -pea k h ou r s t o ma ke t h in gs ea sier f or ot h er In t er n et u ser s-it t a kes a wh il e.) Th is f il e is qu it e l a r ge beca u se it con t a in s a l l t h e sou r ce f il es f or Per l bu n dl ed t oget h er in t o a sin gl e f il e. Th e quit comma n d discon n ect s f r om t h e MIT sou r ce r eposit or y a n d r et u r n s you t o you r own syst em.

On ce you 've r et r ieved t h e Per l dist r ibu t ion , do t h e f ol l owin g: 1. Cr ea t e a dir ect or y a n d move t h e f il e you ju st r eceived, perl-5.001.tar.gz, t o t h is dir ect or y. (Or , a l t er n a t ivel y, move it t o a dir ect or y a l r ea dy r eser ved f or t h is pu r pose.) 2. Th e perl-5.001.tar.gz f il e is compr essed t o sa ve spa ce. To u n compr ess it , en t er t h e comma n d $ gunzip perl-5.001.tar.gz gunzipis t h e GNU u n compr ess pr ogr a m. If it 's n ot a va il a bl e on you r syst em, see

you r syst em a dmin ist r a t or . (You ca n , in f a ct , r et r ieve it f r om prep.ai.mit.eduu sin g a n on ymou s FTP wit h t h e sa me comma n ds you u sed t o r et r ieve t h e Per l dist r ibu t ion .) Wh en you r u n gunzip, t h e f il e perl-5.001.tar.gzwil l be r epl a ced by perl5.001.tar, wh ich is t h e u n compr essed ver sion of t h e Per l dist r ibu t ion f il e. 3. Th e n ext st ep is t o u n pa ck t h e Per l dist r ibu t ion . In ot h er wor ds, u se t h e in f or ma t ion in t h e Per l dist r ibu t ion t o cr ea t e t h e Per l sou r ce f il es. To do t h is, en t er t h e f ol l owin g comma n d: $ tar xvf - /u/jqpublic/outfile");

Th is open s t h e f il e /u/jqpublic/outfile f or wr it in g a n d a ssocia t es it wit h t h e f il e va r ia bl e OUTFILE. To specif y a ppen d mode, pu t t wo > ch a r a ct er s in f r on t of t h e f il en a me, a s f ol l ows:

open (APPENDFILE, ">>/u/jqpublic/appendfile");

Th is open s t h e f il e /u/jqpublic/appendfile in a ppen d mode a n d a ssocia t es it wit h t h e f il e va r ia bl e APPENDFILE. NOTE Her e a r e a f ew t h in gs t o r emember wh en open in g f il es: ●





Wh en you open a f il e f or wr it in g, a n y exist in g con t en t s a r e dest r oyed. You ca n n ot r ea d f r om a n d wr it e t o t h e sa me f il e a t t h e sa me t ime. Wh en you open a f il e in a ppen d mode, t h e exist in g con t en t s a r e n ot dest r oyed, bu t you ca n n ot r ea d t h e f il e wh il e wr it in g t o it .

Checking Whether the Open Succeeded Bef or e you ca n u se a f il e open ed by t h e open f u n ct ion , you sh ou l d f ir st ch eck wh et h er t h e open f u n ct ion a ct u a l l y is givin g you a ccess t o t h e f il e. Th e open f u n ct ion en a bl es you t o do t h is by r et u r n in g a va l u e in dica t in g wh et h er t h e f il e-open in g oper a t ion su cceeded: ● ●

If open r et u r n s a n on z er o va l u e, t h e f il e h a s been open ed su ccessf u l l y. If open r et u r n s 0, a n er r or h a s occu r r ed.

As you ca n see, t h e va l u es r et u r n ed by open cor r espon d t o t h e va l u es f or t r u e a n d f a l se in con dit ion a l expr ession s. Th is mea n s t h a t you ca n u se open in if a n d unless st a t emen t s. Th e f ol l owin g is a n exa mpl e: if (open(MYFILE, "/u/jqpublic/myfile")) { # here's what to do if the file opened }

Th e code in side t h e if st a t emen t is execu t ed on l y if t h e f il e h a s been su ccessf u l l y open ed. Th is en su r es t h a t you r pr ogr a ms r ea d or wr it e on l y t o f il es t h a t you ca n a ccess. NOTE

If open r et u r n s f a l se, you ca n f in d ou t wh a t wen t wr on g by u sin g t h e f il e-t est oper a t or s, wh ich you 'l l l ea r n a bou t l a t er t oda y.

Reading from a File On ce you h a ve open ed a f il e a n d det er min ed t h a t t h e f il e is a va il a bl e f or u se, you ca n r ea d in f or ma t ion f r om it . To r ea d f r om a f il e, en cl ose t h e f il e va r ia bl e a ssocia t ed wit h t h e f il e in a n gl e br a cket s (< a n d >), a s f ol l ows:

$line = ;

Th is st a t emen t r ea ds a l in e of in pu t f r om t h e f il e specif ied by t h e f il e va r ia bl e MYFILE a n d st or es t h e l in e of in pu t in t h e sca l a r va r ia bl e $line. List in g 6.1 is a simpl e pr ogr a m t h a t r ea ds in pu t f r om a f il e a n d wr it es it t o t h e st a n da r d ou t pu t f il e.

List ing 6.1. A pr o g r am t hat r e ads l ine s f r o m a f il e and pr int s t he m. 1:

#!/usr/local/bin/perl

2: 3:

if (open(MYFILE, "file1")) {

4:

$line = ;

5:

while ($line ne "") {

6:

print ($line);

7:

$line = ;

8: 9:

} }

$ program6_1 Here is a line of input. Here is another line of input. Here is the last line of input. $

Lin e 3 open s t h e f il e file1 in r ea d mode, wh ich mea n s t h a t t h e f il e is t o be ma de a va il a bl e f or r ea din g. file1 is a ssu med t o be in t h e cu r r en t wor kin g dir ect or y. Th e f il e va r ia bl e MYFILE is a ssocia t ed wit h t h e f il e file1. If t h e ca l l t o open r et u r n s a n on z er o va l u e, t h e con dit ion a l expr ession

open(MYFILE, "file1")

is a ssu med t o be t r u e, a n d t h e code in side t h e if st a t emen t is execu t ed. Lin es 4-8 pr in t t h e con t en t s of file1. Th e sa mpl e ou t pu t sh own h er e a ssu mes t h a t file1 con t a in s t h e f ol l owin g t h r ee l in es: Here is a line of input. Here is another line of input. Here is the last line of input.

Lin e 4 r ea ds t h e f ir st l in e of in pu t f r om t h e f il e specif ied by t h e f il e va r ia bl e MYFILE, wh ich is file1. Th is l in e of in pu t is st or ed in t h e sca l a r va r ia bl e $line. Lin e 5 t est s wh et h er t h e en d of t h e f il e specif ied by MYFILE h a s been r ea ch ed. If t h er e a r e n o mor e l in es l ef t in MYFILE, $line is a ssign ed t h e empt y st r in g. Lin e 6 pr in t s t h e t ext st or ed in $line, wh ich is t h e l in e of in pu t r ea d f r om MYFILE.

Lin e 7 r ea ds t h e n ext l in e of MYFILE, pr epa r in g f or t h e l oop t o st a r t a ga in .

File Variables and the Standard Input File Now t h a t you h a ve seen h ow Per l pr ogr a ms r ea d in pu t f r om f il es in r ea d mode, t a ke a n ot h er l ook a t a st a t emen t t h a t r ea ds a l in e of in pu t f r om t h e st a n da r d in pu t f il e. $line = ;

Her e's wh a t is a ct u a l l y h a ppen in g: Th e Per l pr ogr a m is r ef er en cin g t h e f il e va r ia bl e STDIN, wh ich r epr esen t s t h e st a n da r d in pu t f il e. Th e < a n d > on eit h er side of STDIN t el l t h e Per l in t er pr et er t o r ea d a l in e of in pu t f r om t h e st a n da r d in pu t f il e, ju st a s t h e < a n d > on eit h er side of MYFILE in

$line = ;

t el l t h e Per l in t er pr et er t o r ea d a l in e of in pu t f r om MYFILE. STDIN is a f il e va r ia bl e t h a t beh a ves l ike a n y ot h er f il e va r ia bl e r epr esen t in g a f il e in r ea d mode. Th e on l y dif f er en ce is t h a t STDIN does n ot n eed t o be open ed by t h e open

f u n ct ion beca u se t h e Per l in t er pr et er does t h a t f or you .

Terminating a Program Using die In List in g 6.1, you sa w t h a t t h e r et u r n va l u e f r om open ca n be t est ed t o see wh et h er t h e pr ogr a m a ct u a l l y h a s a ccess t o t h e f il e. Th e code t h a t oper a t es on t h e open ed f il e is con t a in ed in a n if st a t emen t . If you a r e wr it in g a l a r ge pr ogr a m, you migh t n ot wa n t t o pu t a l l of t h e code t h a t a f f ect s a f il e in side a n if st a t emen t , beca u se t h e dist a n ce bet ween t h e begin n in g of t h e if st a t emen t a n d t h e cl osin g br a ce (}) cou l d get ver y l a r ge. For exa mpl e:

if (open(MYFILE, "file1")) { # this could be many pages of statements! }

Besides, a f t er a wh il e, you 'l l pr oba bl y get t ir ed of t ypin g t h e spa ces or t a bs you u se t o in den t t h e code in side t h e if st a t emen t . Per l pr ovides a wa y a r ou n d t h is u sin g t h e l ibr a r y f u n ct ion die.

Th e syn t a x f or t h e die l ibr a r y f u n ct ion is

die (message);

Wh en t h e Per l in t er pr et er execu t es t h e die f u n ct ion , t h e pr ogr a m t er min a t es immedia t el y a n d pr in t s t h e messa ge pa ssed t o die. For exa mpl e, t h e st a t emen t die ("Stop this now!\n");

pr in t s t h e f ol l owin g on you r scr een a n d t er min a t es t h e pr ogr a m: Stop this now!

List in g 6.2 sh ows h ow you ca n u se die t o smoot h l y t est wh et h er a f il e h a s been open ed cor r ect l y.

List ing 6.2. A pr o g r am t hat use s die whe n t e st ing f o r a suc c e ssf ul f il e o pe n o pe r at io n. 1:

#!/usr/local/bin/perl

2: 3:

unless (open(MYFILE, "file1")) {

4: 5:

die ("cannot open input file file1\n"); }

6: 7:

# if the program gets this far, the file was

8:

# opened successfully

9:

$line = ;

10: while ($line ne "") { 11:

print ($line);

12:

$line = ;

13: }

$ program6_2 Here is a line of input. Here is another line of input. Here is the last line of input. $

Th is pr ogr a m beh a ves t h e sa me wa y a s t h e on e in List in g 6.1, except t h a t it pr in t s ou t a n er r or messa ge wh en it ca n 't open t h e f il e. Lin e 3 open s t h e f il e a n d t est s wh et h er t h e f il e open ed su ccessf u l l y. Beca u se t h is is a n unless st a t emen t , t h e code in side t h e br a ces ({ a n d }) is execu t ed u n l ess t h e f il e open ed su ccessf u l l y. Lin e 4 is t h e ca l l t o die t h a t is execu t ed if t h e f il e does n ot open su ccessf u l l y. Th is st a t emen t pr in t s t h e f ol l owin g messa ge on t h e scr een a n d exit s: cannot open input file file1

Beca u se l in e 4 t er min a t es pr ogr a m execu t ion wh en t h e f il e is n ot open , t h e pr ogr a m ca n ma ke it pa st l in e 5 on l y if t h e f il e h a s been open ed su ccessf u l l y. Th e l oop in l in es 9-13 is iden t ica l t o t h e l oop you sa w in List in g 6.1. Th e on l y dif f er en ce is t h a t t h is l oop is n o l on ger in side a n if st a t emen t . NOTE

Her e is a n ot h er wa y t o wr it e l in es 3-5: open (MYFILE, "file1") || die ("Could not open file");

Reca l l t h a t t h e l ogica l OR oper a t or on l y eva l u a t es t h e expr ession on it s r igh t if t h e expr ession on it s l ef t is f a l se. Th is mea n s t h a t die is ca l l ed on l y if open r et u r n s f a l se (if t h e open oper a t ion f a il s).

Printing Error Information Using die If you l ike, you ca n h a ve die pr in t t h e n a me of t h e Per l pr ogr a m a n d t h e l in e n u mber of t h e st a t emen t con t a in in g t h e ca l l t o die. To do t h is, l ea ve of f t h e t r a il in g n ewl in e ch a r a ct er in t h e ch a r a ct er st r in g, a s f ol l ows: die ("Missing input file");

If t h e Per l pr ogr a m con t a in in g t h is st a t emen t is ca l l ed myprog, a n d t h is st a t emen t is l in e 14 of myprog, t h is ca l l t o die pr in t s t h e f ol l owin g a n d exit s:

Missing input file at myprog line 14.

Compa r e t h is wit h die ("Missing input file\n");

wh ich simpl y pr in t s t h e f ol l owin g bef or e exit in g: Missing input file

Specif yin g t h e pr ogr a m n a me a n d l in e n u mber is u sef u l in t wo ca ses: ●



If t h e pr ogr a m con t a in s ma n y simil a r er r or messa ges, you ca n u se die t o specif y t h e l in e n u mber of t h e messa ge t h a t a ct u a l l y a ppea r ed. If t h e pr ogr a m is ca l l ed f r om wit h in a n ot h er pr ogr a m, you ca n u se die t o in dica t e t h a t t h is pr ogr a m gen er a t ed t h e er r or .

Reading into Array Variables Per l en a bl es you t o r ea d a n en t ir e f il e in t o a sin gl e a r r a y va r ia bl e. To do t h is, a ssign t h e f il e va r ia bl e t o t h e a r r a y va r ia bl e, a s f ol l ows: @array = ;

Th is r ea ds t h e en t ir e f il e r epr esen t ed by MYFILE in t o t h e a r r a y va r ia bl e @array. Ea ch l in e of t h e f il e becomes a n el emen t of t h e l ist t h a t is st or ed in @array. List in g 6.3 is a simpl e pr ogr a m t h a t r ea ds a n en t ir e f il e in t o a n a r r a y.

List ing 6.3. A pr o g r am t hat r e ads an e nt ir e input f il e int o an ar r ay. 1:

#!/usr/local/bin/perl

2: 3:

unless (open(MYFILE, "file1")) {

4:

die ("cannot open input file file1\n");

5:

}

6:

@input = ;

7:

print (@input);

$ program6_3 Here is a line of input. Here is another line of input. Here is the last line of input.

$

Lin es 3-5 open t h e f il e, t est wh et h er t h e f il e h a s been open ed su ccessf u l l y, a n d t er min a t e t h e pr ogr a m if t h e f il e ca n n ot be open ed. Lin e 6 r ea ds t h e en t ir e con t en t s of t h e f il e r epr esen t ed by MYFILE in t o t h e a r r a y va r ia bl e @input. @input n ow con t a in s a l ist con sist in g of t h e f ol l owin g t h r ee el emen t s:

("Here is a line of input.\n", "Here is another line of input.\n", "Here is the last line of input.\n")

Not e t h a t a n ewl in e ch a r a ct er is in cl u ded a s t h e l a st ch a r a ct er of ea ch l in e. Lin e 7 u ses t h e print f u n ct ion t o pr in t t h e en t ir e f il e.

Writing to a File Af t er you h a ve open ed a f il e in wr it e or a ppen d mode, you ca n wr it e t o t h e f il e you h a ve open ed by specif yin g t h e f il e va r ia bl e wit h t h e print f u n ct ion . For exa mpl e, if you h a ve open ed a f il e f or wr it in g u sin g t h e st a t emen t open(OUTFILE, ">outfile");

t h e f ol l owin g st a t emen t : print OUTFILE ("Here is an output line.\n");

wr it es t h e f ol l owin g l in e t o t h e f il e specif ied by OUTFILE, wh ich is t h e f il e ca l l ed outfile:

Here is an output line.

List in g 6.4 is a simpl e pr ogr a m t h a t r ea ds f r om on e f il e a n d wr it es t o a n ot h er .

List ing 6.4. A pr o g r am t hat o pe ns t wo f il e s and c o pie s o ne int o ano t he r . 1:

#!/usr/local/bin/perl

2: 3:

unless (open(INFILE, "file1")) {

4:

die ("cannot open input file file1\n");

5:

}

6:

unless (open(OUTFILE, ">outfile")) {

7:

die ("cannot open output file outfile\n");

8:

}

9:

$line = ;

10: while ($line ne "") { 11:

print OUTFILE ($line);

12:

$line = ;

13: }

Th is pr ogr a m wr it es n ot h in g t o t h e scr een beca u se a l l ou t pu t is dir ect ed t o t h e f il e ca l l ed outfile.

Lin es 3-5 open file1 f or r ea din g. If t h e f il e ca n n ot be open ed, l in e 4 is execu t ed, wh ich pr in t s t h e f ol l owin g messa ge on t h e scr een a n d t er min a t es t h e pr ogr a m: cannot open input file file1

Lin es 6-8 open outfile f or wr it in g; t h e > in >outfile in dica t es t h a t t h e f il e is t o be open ed in wr it e mode. If outfile ca n n ot be open ed, l in e 7 pr in t s t h e messa ge

cannot open output file outfile

on t h e scr een a n d t er min a t es t h e pr ogr a m. Th e on l y ot h er l in e in t h e pr ogr a m t h a t you h a ve n ot seen in ot h er l ist in gs in t h is l esson is l in e 11, wh ich wr it es t h e con t en t s of t h e sca l a r va r ia bl e $line on t h e f il e specif ied by OUTFILE. On ce t h is pr ogr a m h a s compl et ed, t h e con t en t s of file1 a r e copied in t o outfile.

Here is a line of input. Here is another line of input. Here is the last line of input.

Ma ke su r e t h a t f il es you open in wr it e mode con t a in n ot h in g va l u a bl e. Wh en t h e open f u n ct ion open s a f il e in wr it e mode, a n y exist in g con t en t s a r e dest r oyed.

The Standard Output File Variable If you wa n t , you r pr ogr a m ca n r ef er en ce t h e st a n da r d ou t pu t f il e by r ef er r in g t o t h e f il e va r ia bl e a ssocia t ed wit h t h e ou t pu t f il e. Th is f il e va r ia bl e is n a med STDOUT. By def a u l t , t h e print st a t emen t sen ds ou t pu t t o t h e st a n da r d ou t pu t f il e, wh ich mea n s t h a t it sen ds t h e ou t pu t t o t h e f il e a ssocia t ed wit h STDOUT. As a con sequ en ce, t h e f ol l owin g st a t emen t s a r e equ iva l en t : print ("Here is a line of output.\n"); print STDOUT ("Here is a line of output.\n");

NOTE

You do n ot n eed t o open STDOUT beca u se Per l a u t oma t ica l l y open s it f or you .

Merging Two Files into One In Per l , you ca n open a s ma n y f il es a s you l ike, pr ovided you def in e a dif f er en t f il e va r ia bl e f or ea ch on e. (Act u a l l y, t h er e is a n u pper l imit on t h e n u mber of f il es you ca n open , bu t it 's f a ir l y l a r ge a n d a l so syst em-depen den t .) For a n exa mpl e of a pr ogr a m t h a t h a s mu l t ipl e f il es open a t on e t ime, t a ke a l ook a t List in g 6.5. Th is pr ogr a m mer ges t wo f il es by cr ea t in g a n ou t pu t f il e con sist in g of on e l in e f r om t h e f ir st f il e, on e l in e f r om t h e secon d f il e, a n ot h er l in e f r om t h e f ir st f il e, a n d so on . For exa mpl e, if a n in pu t f il e n a med merge1 con t a in s t h e l in es

a1 a2 a3

a n d a n ot h er f il e, merge2, con t a in s t h e l in es

b1 b2 b3

t h en t h e r esu l t in g ou t pu t f il e con sist s of a1 b1 a2 b2 a3 b3

List ing 6.5. A pr o g r am t hat me r g e s t wo f il e s. 1:

#!/usr/local/bin/perl

2: 3:

open (INFILE1, "merge1") ||

4: 5:

die ("Cannot open input file merge1\n"); open (INFILE2, "merge2") ||

6:

die ("Cannot open input file merge2\n");

7:

$line1 = ;

8:

$line2 = ;

9:

while ($line1 ne "" || $line2 ne "") {

10:

if ($line1 ne "") {

11:

print ($line1);

12:

$line1 = ;

13:

}

14:

if ($line2 ne "") {

15:

print ($line2);

16:

$line2 = ;

17: 18: }

}

$ program6_5 a1 b1 a2

b2 a3 b3 $

Lin es 3 a n d 4 sh ow a n ot h er wa y t o wr it e a st a t emen t t h a t eit h er open s a f il e or ca l l s die if t h e open f a il s. Reca l l t h a t t h e || oper a t or f ir st eva l u a t es it s l ef t oper a n d; if t h e l ef t oper a n d eva l u a t es t o t r u e (a n on z er o va l u e), t h e r igh t oper a n d is n ot eva l u a t ed beca u se t h e r esu l t of t h e expr ession is t r u e. Beca u se of t h is, t h e r igh t oper a n d, t h e ca l l t o die, is eva l u a t ed on l y wh en t h e l ef t oper a n d is f a l se-wh ich h a ppen s on l y wh en t h e ca l l t o open f a il s a n d t h e f il e merge1 ca n n ot be open ed. Lin es 5 a n d 6 r epea t t h e pr ecedin g pr ocess f or t h e f il e merge2. Aga in , eit h er t h e f il e is open ed su ccessf u l l y or t h e pr ogr a m a bor t s by ca l l in g die. Th e pr ogr a m t h en l oops r epea t edl y, r ea din g a l in e of in pu t f r om ea ch f il e ea ch t ime. Th e l oop t er min a t es on l y wh en bot h f il es h a ve been exh a u st ed. If on e f il e is empt y bu t t h e ot h er is n ot , t h e pr ogr a m ju st copies t h e l in e f r om t h e n on -empt y f il e t o t h e st a n da r d ou t pu t f il e. Not e t h a t t h e ou t pu t f r om t h is pr ogr a m is pr in t ed on t h e scr een . If you decide t h a t you wa n t t o sen d t h is ou t pu t t o a f il e, you ca n do on e of t wo t h in gs: ●



You ca n modif y t h e pr ogr a m t o wr it e it s ou t pu t t o a dif f er en t f il e. To do t h is, open t h e f il e in wr it e mode a n d a ssocia t e it wit h a f il e va r ia bl e. Th en , ch a n ge t h e print st a t emen t s t o r ef er t o t h is f il e va r ia bl e. You ca n r edir ect t h e st a n da r d ou t pu t f il e on t h e comma n d l in e.

For a discu ssion of t h e secon d met h od, see t h e f ol l owin g sect ion .

Redirecting Standard Input and Standard Output Wh en you r u n pr ogr a ms on UNIX, you ca n r edir ect in pu t a n d ou t pu t u sin g < a n d >, r espect ivel y, a s f ol l ows: myprog output

Her e, wh en you r u n t h e pr ogr a m ca l l ed myprog, t h e in pu t f or t h e pr ogr a m is t a ken f r om t h e f il e specif ied by input in st ea d of f r om t h e keyboa r d, a n d t h e ou t pu t f or t h e pr ogr a m is sen t t o t h e f il e specif ied by output in st ea d of t o t h e scr een . Wh en you r u n a Per l pr ogr a m a n d r edir ect in pu t u sin g 0) { $string = ; $string =~ /abc/$var/o; print ($string); $var--;

# the replacement string is still "17"

}

Aga in , a s wit h t h e ma t ch oper a t or , t h er e is n o r ea l r ea son t o u se t h e o opt ion .

Treating the String as Single or Multiple Lines As in t h e pa t t er n -ma t ch in g oper a t or , t h e s a n d m opt ion s specif y t h a t t h e st r in g t o be ma t ch ed is t o be t r ea t ed a s a sin gl e l in e or a s mu l t ipl e l in es, r espect ivel y. Th e s opt ion en su r es t h a t t h e n ewl in e ch a r a ct er \n is ma t ch ed by t h e . specia l ch a r a ct er . $string = "This is a\ntwo-line string."; $string =~ s/a.*o/one/s; # $string now contains "This is a one-line string."

If t h e m opt ion is specif ied, ^ a n d $ ma t ch t h e begin n in g a n d en d of a n y l in e.

$string = "The The first line\nThe The second line"; $string =~ s/^The//gm; # $string now contains "The first line\nThe second line" $string =~ s/e$/k/gm; # $string now contains "The first link\nThe second link"

Th e \A a n d \Z esca pe sequ en ces (def in ed in Per l 5) a l wa ys ma t ch on l y t h e begin n in g a n d en d of t h e st r in g, r espect ivel y. (Th is is t h e on l y ca se wh er e \A a n d \Z beh a ve dif f er en t l y f r om ^ a n d $.)

NOTE Th e m a n d s opt ion s a r e def in ed on l y in Per l 5. To t r ea t a st r in g a s mu l t ipl e l in es wh en you r u n Per l 4, set t h e $* syst em va r ia bl e, descr ibed on Da y 17.

Using White Space in Patterns Th e x opt ion t el l s t h e Per l in t er pr et er t o ign or e a l l wh it e spa ce u n l ess pr eceded by a ba cksl a sh . As wit h t h e pa t t er n -ma t ch in g oper a t or , ign or in g wh it e spa ce ma kes compl ica t ed st r in g pa t t er n s ea sier t o r ea d. $string =~ s/\d{2} ([\W]) \d{2} \1 \d{2}/$1-$2-$3/x

Th is con ver t s a da y-mon t h -yea r st r in g t o t h e dd-mm-yy f or ma t . NOTE Even if t h e x opt ion is specif ied, spa ces in t h e r epl a cemen t st r in g a r e n ot ign or ed. For exa mpl e, t h e f ol l owin g r epl a ces 14/04/95 wit h 14 - 04 - 95, n ot 14-04-95: $string =~ s/\d{2} ([\W]) \d{2} \1 \d{2}/$1 - $2 $3/x

Al so n ot e t h a t t h e x opt ion is def in ed on l y in Per l 5.

Specifying a Different Delimiter You ca n specif y a dif f er en t del imit er t o sepa r a t e t h e pa t t er n a n d r epl a cemen t st r in g in t h e su bst it u t ion oper a t or . For exa mpl e, t h e f ol l owin g su bst it u t ion oper a t or r epl a ces /u/bin wit h /usr/local/bin:

s#/u/bin#/usr/local/bin#

Th e sea r ch a n d r epl a cemen t st r in gs ca n be en cl osed in pa r en t h eses or a n gl e br a cket s. s(/u/bin)(/usr/local/bin) s/\/usr\/local\/bin/

NOTE As wit h t h e ma t ch oper a t or , you ca n n ot u se a specia l ch a r a ct er bot h a s a del imit er a n d in a pa t t er n . s.a.c.def.

Th is su bst it u t ion wil l be f l a gged a s con t a in in g a n er r or beca u se t h e . ch a r a ct er is bein g u sed a s t h e del imit er . Th e su bst it u t ion s.a\.c.def.

does wor k, bu t it su bst it u t es def f or a.c, wh er e . is a n a ct u a l per iod a n d n ot t h e pa t t er n specia l ch a r a ct er .

The Translation Operator Per l a l so pr ovides a n ot h er wa y t o su bst it u t e on e gr ou p of ch a r a ct er s f or a n ot h er : t h e tr t r a n sl a t ion oper a t or . Th is oper a t or u ses t h e f ol l owin g syn t a x:

tr/string1/string2/

Her e, string1 con t a in s a l ist of ch a r a ct er s t o be r epl a ced, a n d string2 con t a in s t h e ch a r a ct er s t h a t r epl a ce t h em. Th e f ir st ch a r a ct er in string1 is r epl a ced by t h e f ir st ch a r a ct er in string2, t h e secon d ch a r a ct er in string1 is r epl a ced by t h e secon d ch a r a ct er in string2, a n d so on . Her e is a simpl e exa mpl e: $string = "abcdefghicba";

$string =~ tr/abc/def/;

Her e, t h e ch a r a ct er s a, b, a n d c a r e t o be r epl a ced a s f ol l ows: ● ● ●

Al l occu r r en ces of t h e ch a r a ct er a a r e t o be r epl a ced by t h e ch a r a ct er d. Al l occu r r en ces of t h e ch a r a ct er b a r e t o be r epl a ced by t h e ch a r a ct er e. Al l occu r r en ces of t h e ch a r a ct er c a r e t o be r epl a ced by t h e ch a r a ct er f.

Af t er t h e t r a n sl a t ion , t h e sca l a r va r ia bl e $string con t a in s t h e va l u e defdefghifed. NOTE If t h e st r in g l ist in g t h e ch a r a ct er s t o be r epl a ced is l on ger t h a n t h e st r in g con t a in in g t h e r epl a cemen t ch a r a ct er s, t h e l a st ch a r a ct er of t h e r epl a cemen t st r in g is r epea t ed. For exa mpl e: $string = "abcdefgh"; $string =~ tr/efgh/abc/;

Her e, t h er e is n o ch a r a ct er cor r espon din g t o d in t h e r epl a cemen t l ist , so c, t h e l a st ch a r a ct er in t h e r epl a cemen t l ist , r epl a ces h. Th is t r a n sl a t ion set s t h e va l u e of $string t o abcdabcc. Al so n ot e t h a t if t h e sa me ch a r a ct er a ppea r s mor e t h a n on ce in t h e l ist of ch a r a ct er s t o be r epl a ced, t h e f ir st r epl a cemen t is u sed:

$string =~ tr/AAA/XYZ/; replaces A with X

Th e most common u se of t h e t r a n sl a t ion oper a t or is t o con ver t a l ph a bet ic ch a r a ct er s f r om u pper ca se t o l ower ca se or vice ver sa . List in g 7.13 pr ovides a n exa mpl e of a pr ogr a m t h a t con ver t s a f il e t o a l l l ower ca se ch a r a ct er s.

List ing 7.13. An uppe r c ase -t o -l o we r c ase c o nve r sio n pr o g r am.

1:

#!/usr/local/bin/perl

2: 3:

while ($line = ) {

4:

$line =~ tr/A-Z/a-z/;

5:

print ($line);

6:

}

$ program7_13 THIS LINE IS IN UPPER CASE. this line is in upper case. ThiS LiNE Is iN mIxED cASe. this line is in mixed case. ^D $

Th is pr ogr a m r ea ds a l in e a t a t ime f r om t h e st a n da r d in pu t f il e, t er min a t in g wh en it sees a l in e con t a in in g t h e Ct r l +D (en d-of -f il e) ch a r a ct er . Lin e 4 per f or ms t h e t r a n sl a t ion oper a t ion . As in t h e ot h er pa t t er n -ma t ch in g oper a t ion s, t h e r a n ge ch a r a ct er (-) in dica t es a r a n ge of ch a r a ct er s t o be in cl u ded. Her e, t h e r a n ge a-z r ef er s t o a l l t h e l ower ca se ch a r a ct er s, a n d t h e r a n ge A-Z r ef er s t o a l l t h e u pper ca se ch a r a ct er s. NOTE

Th er e a r e t wo t h in gs you sh ou l d n ot e a bou t t h e t r a n sl a t ion oper a t or : Th e pa t t er n specia l ch a r a ct er s a r e n ot su ppor t ed by t h e t r a n sl a t ion oper a t or . You ca n u se y in pl a ce of tr if you wa n t . $string =~ y/a-z/A-Z/;

Options for the Translation Operator Th e t r a n sl a t ion oper a t or su ppor t s t h r ee opt ion s, wh ich a r e l ist ed in Ta bl e 7.6. Th e c opt ion (c is f or "compl emen t ") t r a n sl a t es a l l ch a r a ct er s t h a t a r e n ot specif ied. For exa mpl e, t h e st a t emen t $string =~ tr/\d/ /c;

r epl a ces ever yt h in g t h a t is n ot a digit wit h a spa ce. Tabl e 7.6. Opt io ns f o r t he t r ansl at io n o pe r at o r . Opt io n De sc r ipt io n c

Tr a n sl a t e a l l ch a r a ct er s n ot specif ied

d

Del et e a l l specif ied ch a r a ct er s

s

Repl a ce mu l t ipl e iden t ica l ou t pu t ch a r a ct er s wit h a sin gl e ch a r a ct er

Th e d opt ion del et es ever y specif ied ch a r a ct er .

$string =~ tr/\t //d;

Th is del et es a l l t h e t a bs a n d spa ces f r om $string. Th e s opt ion (f or "squ eez e") ch ecks t h e ou t pu t f r om t h e t r a n sl a t ion . If t wo or mor e con secu t ive ch a r a ct er s t r a n sl a t e t o t h e sa me ou t pu t ch a r a ct er , on l y on e ou t pu t ch a r a ct er is a ct u a l l y u sed. For exa mpl e, t h e f ol l owin g r epl a ces ever yt h in g t h a t is n ot

a digit a n d ou t pu t s on l y on e spa ce bet ween digit s: $string =~ tr/0-9/ /cs;

List in g 7.14 is a simpl e exa mpl e of a pr ogr a m t h a t u ses some of t h ese t r a n sl a t ion opt ion s. It r ea ds a n u mber f r om t h e st a n da r d in pu t f il e, a n d it get s r id of ever y in pu t ch a r a ct er t h a t is n ot a ct u a l l y a digit .

List ing 7.14. A pr o g r am t hat e nsur e s t hat a st r ing c o nsist s o f no t hing but dig it s. 1:

#!/usr/local/bin/perl

2: 3:

$string = ;

4:

$string =~ tr/0-9//cd;

5:

print ("$string\n");

$ program7_14 The number 45 appears in this string. 45 $

Lin e 4 of t h is pr ogr a m per f or ms t h e t r a n sl a t ion . Th e d opt ion in dica t es t h a t t h e t r a n sl a t ed ch a r a ct er s a r e t o be del et ed, a n d t h e c opt ion in dica t es t h a t ever y ch a r a ct er n ot in t h e l ist is t o be del et ed. Th er ef or e, t h is t r a n sl a t ion del et es ever y ch a r a ct er in t h e st r in g t h a t is n ot a digit . Not e t h a t t h e t r a il in g n ewl in e ch a r a ct er is n ot a digit , so it is on e of t h e ch a r a ct er s del et ed.

Extended Pattern-Matching Per l 5 pr ovides some a ddit ion a l pa t t er n -ma t ch in g ca pa bil it ies n ot f ou n d in Per l 4 or in st a n da r d UNIX pa t t er n -ma t ch in g oper a t ion s. Ext en ded pa t t er n -ma t ch in g ca pa bil it ies empl oy t h e f ol l owin g syn t a x: (?pattern)

is a sin gl e ch a r a ct er r epr esen t in g t h e ext en ded pa t t er n -ma t ch in g ca pa bil it y bein g u sed, a n d pattern is t h e pa t t er n or su bpa t t er n t o be a f f ect ed.

Th e f ol l owin g ext en ded pa t t er n -ma t ch in g ca pa bil it ies a r e su ppor t ed by Per l 5: ● ● ● ●

Pa r en t h esiz in g su bpa t t er n s wit h ou t sa vin g t h em in memor y Embeddin g opt ion s in pa t t er n s Posit ive a n d n ega t ive l ook-a h ea d con dit ion s Commen t s

Parenthesizing Without Saving in Memory In Per l , wh en a su bpa t t er n is en cl osed in pa r en t h eses, t h e su bpa t t er n is a l so st or ed in memor y. If you wa n t t o en cl ose a su bpa t t er n in pa r en t h eses wit h ou t st or in g it in memor y, u se t h e ?: ext en ded pa t t er n -ma t ch in g f ea t u r e. For exa mpl e, con sider t h is pa t t er n : /(?:a|b|c)(d|e)f\1/

Th is ma t ch es t h e f ol l owin g:



On e of a, b, or c On e of d or e



f



Wh ich ever of d or e wa s ma t ch ed ea r l ier



Her e, \1 ma t ch es eit h er d or e, beca u se t h e su bpa t t er n a|b|c wa s n ot st or ed in memor y. Compa r e t h is wit h t h e f ol l owin g: /(a|b|c)(d|e)f\1/

Her e, t h e su bpa t t er n a|b|c is st or ed in memor y, a n d on e of a, b, or c is ma t ch ed by \1.

Embedding Pattern Options Per l 5 pr ovides a wa y of specif yin g a pa t t er n -ma t ch in g opt ion wit h in t h e pa t t er n it sel f . For exa mpl e, t h e f ol l owin g pa t t er n s a r e equ iva l en t : /[a-z]+/i /(?i)[a-z]+/

In bot h ca ses, t h e pa t t er n ma t ch es on e or mor e a l ph a bet ic ch a r a ct er s; t h e i opt ion in dica t es t h a t ca se is t o be ign or ed wh en ma t ch in g. Th e syn t a x f or embedded pa t t er n opt ion s is (?option)

wh er e option is on e of t h e opt ion s sh own in Ta bl e 7.7. Tabl e 7.7. Opt io ns f o r e mbe dde d pat t e r ns. Opt io n

De sc r ipt io n

i

Ign or e ca se in pa t t er n

m

Tr ea t pa t t er n a s mu l t ipl e l in es

s

Tr ea t pa t t er n a s sin gl e l in e

x

Ign or e wh it e spa ce in pa t t er n

Th e g a n d o opt ion s a r e n ot su ppor t ed a s embedded pa t t er n opt ion s. Embedded pa t t er n opt ion s give you mor e f l exibil it y wh en you a r e ma t ch in g pa t t er n s. For exa mpl e: $pattern1 = "[a-z0-9]+"; $pattern2 = "(?i)[a-z]+"; if ($string =~ /$pattern1|$pattern2/) { ...

}

Her e, t h e i opt ion is specif ied f or some, bu t n ot a l l , of a pa t t er n . (Th is pa t t er n ma t ch es eit h er a n y col l ect ion of l ower ca se l et t er s mixed wit h digit s, or a n y col l ect ion of l et t er s.)

Positive and Negative Look-Ahead Per l 5 en a bl es you t o u se t h e ?= f ea t u r e t o def in e a bou n da r y con dit ion t h a t mu st be ma t ch ed in or der f or t h e pa t t er n t o ma t ch . For exa mpl e, t h e f ol l owin g pa t t er n ma t ch es abc on l y if it is f ol l owed by def:

/abc(?=def)/

Th is is kn own a s a positive look-ahead condition. NOTE Th e posit ive l ook-a h ea d con dit ion is n ot pa r t of t h e pa t t er n ma t ch ed. For exa mpl e, con sider t h ese st a t emen t s: $string = "25abc8"; $string =~ /abc(?=[0-9])/; $matched = $&;

Her e, a s a l wa ys, $& con t a in s t h e ma t ch ed pa t t er n , wh ich in t h is ca se is abc, n ot abc8.

Simil a r l y, t h e ?! f ea t u r e def in es a negative look-ahead condition, wh ich is a bou n da r y con dit ion t h a t mu st n ot be pr esen t if t h e pa t t er n is t o ma t ch . For exa mpl e, t h e pa t t er n /abc(?!def)/ ma t ch es a n y occu r r en ce of abc u n l ess it is f ol l owed by def.

Pattern Comments Per l 5 en a bl es you t o a dd commen t s t o a pa t t er n u sin g t h e ?# f ea t u r e. For exa mpl e:

if ($string =~ /(?i)[a-z]{2,3}(?# match two or three alphabetic characters)/ { ...

}

Addin g commen t s ma kes it ea sier t o f ol l ow compl ica t ed pa t t er n s.

Summary Per l en a bl es you t o sea r ch f or sequ en ces of ch a r a ct er s u sin g patterns. If a pa t t er n is f ou n d in a st r in g, t h e pa t t er n is sa id t o be matched. Pa t t er n s of t en a r e u sed in con ju n ct ion wit h t h e pa t t er n -ma t ch oper a t or s, =~ a n d !~. Th e =~ oper a t or r et u r n s t r u e if t h e pa t t er n ma t ch es, a n d t h e !~ oper a t or r et u r n s t r u e if t h e pa t t er n does n ot ma t ch . Specia l -pa t t er n ch a r a ct er s en a bl e you t o sea r ch f or a st r in g t h a t meet s on e of a va r iet y of con dit ion s. ● ● ● ● ●

● ●

Th e + ch a r a ct er ma t ch es on e or mor e occu r r en ces of a ch a r a ct er . Th e * ch a r a ct er ma t ch es z er o or mor e occu r r en ces of a ch a r a ct er . Th e [] ch a r a ct er s en cl ose a set of ch a r a ct er s, a n y on e of wh ich ma t ch es. Th e ? ch a r a ct er ma t ch es z er o or on e occu r r en ces of a ch a r a ct er . Th e ^ a n d $ ch a r a ct er s ma t ch t h e begin n in g a n d en d of a l in e, r espect ivel y. Th e \b a n d \B ch a r a ct er s ma t ch a wor d bou n da r y or somewh er e ot h er t h a n a wor d bou n da r y, r espect ivel y. Th e {} ch a r a ct er s specif y t h e n u mber of occu r r en ces of a ch a r a ct er . Th e | ch a r a ct er specif ies a l t er n a t ives, eit h er of wh ich ma t ch .

To give a specia l ch a r a ct er it s n a t u r a l mea n in g in a pa t t er n , pr ecede it wit h a ba cksl a sh \. En cl osin g a pa r t of a pa t t er n in pa r en t h eses st or es t h e ma t ch ed su bpa t t er n in memor y; t h is st or ed su bpa t t er n ca n be r eca l l ed u sin g t h e ch a r a ct er sequ en ce \n, a n d st or ed in a sca l a r va r ia bl e u sin g t h e bu il t -in sca l a r va r ia bl e $n. Th e bu il t -in sca l a r va r ia bl e $& st or es t h e en t ir e ma t ch ed pa t t er n . You ca n su bst it u t e f or sca l a r -va r ia bl e n a mes in pa t t er n s, specif y dif f er en t pa t t er n del imit er s, or su ppl y opt ion s t h a t ma t ch ever y possibl e pa t t er n , ign or e ca se, or per f or m sca l a r -va r ia bl e su bst it u t ion on l y on ce. Th e su bst it u t ion oper a t or , s, en a bl es you t o r epl a ce a ma t ch ed pa t t er n wit h a specif ied st r in g. Opt ion s t o t h e su bst it u t ion oper a t or en a bl e you t o r epl a ce ever y ma t ch ed pa t t er n , ign or e ca se, t r ea t t h e r epl a cin g st r in g a s a n expr ession , or per f or m sca l a r va r ia bl e su bst it u t ion on l y on ce.

Th e t r a n sl a t ion oper a t or , tr, en a bl es you t o t r a n sl a t e on e set of ch a r a ct er s in t o a n ot h er set . Opt ion s exist t h a t en a bl e you t o per f or m t r a n sl a t ion on ever yt h in g n ot in t h e l ist , t o del et e ch a r a ct er s in t h e l ist , or t o ign or e mu l t ipl e iden t ica l ou t pu t ch a r a ct er s. Per l 5 pr ovides ext en ded pa t t er n -ma t ch in g ca pa bil it ies n ot pr ovided in Per l 4. To u se on e of t h ese ext en ded pa t t er n f ea t u r es on a su bpa t t er n , pu t (? a t t h e begin n in g of t h e su bpa t t er n a n d ) a t t h e en d of t h e su bpa t t er n .

Q&A Q: A:

Q: A:

Q: A:

Ho w many subpat t e r ns c an be st o r e d in me mo r y using \1, \2, and so o n? Ba sica l l y, a s ma n y a s you l ike. Af t er you st or e mor e t h a n n in e pa t t er n s, you ca n r et r ieve t h e l a t er pa t t er n s u sin g t wo-digit n u mber s pr eceded by a ba cksl a sh , su ch a s \10. Why do e s pat t e r n-me mo r y var iabl e numbe r ing st ar t wit h 1, whe r e as subsc r ipt numbe r ing st ar t s wit h 0? Su bscr ipt n u mber in g st a r t s wit h 0 t o r ema in compa t ibl e wit h t h e C pr ogr a mmin g l a n gu a ge. Th er e is n o su ch t h in g a s pa t t er n memor y in C, so t h er e is n o n eed t o be compa t ibl e wit h it . What happe ns whe n t he r e pl ac e me nt st r ing in t he t r ansl at e c o mmand is l e f t o ut , as in tr/abc//? If t h e r epl a cemen t st r in g is omit t ed, a copy of t h e f ir st st r in g is u sed. Th is mea n s t hat :t:r/abc//

does n ot do a n yt h in g, beca u se it is t h e sa me a s tr/abc/abc/

If t h e r epl a cemen t st r in g is omit t ed in t h e su bst it u t e comma n d, a s in s/abc//

Q: A:

Q: A:

t h e pa t t er n ma t ch ed-in t h is ca se, abc-is del et ed. Why do e s Pe r l use c har ac t e r s suc h as +, *, and ? as pat t e r n spe c ial c har ac t e r s? Th ese specia l ch a r a ct er s u su a l l y cor r espon d t o specia l ch a r a ct er s u sed in ot h er UNIX a ppl ica t ion s, su ch a s vi a n d csh. Some of t h e specia l ch a r a ct er s, su ch a s +, a r e u sed in f or ma l syn t a x descr ipt ion l a n gu a ges. Why do e s Pe r l use bo t h \1 and $1 t o st o r e pat t e r n me mo r y? To en a bl e you t o dist in gu ish bet ween a su bpa t t er n ma t ch ed in t h e cu r r en t pa t t er n (wh ich is st or ed in \1) a n d a su bpa t t er n ma t ch ed in t h e pr eviou s st a t emen t (wh ich is st or ed in $1).

Workshop Th e Wor ksh op pr ovides qu iz qu est ion s t o h el p you sol idif y you r u n der st a n din g of t h e

ma t er ia l cover ed a n d exer cises t o give you exper ien ce in u sin g wh a t you 've l ea r n ed. Tr y a n d u n der st a n d t h e qu iz a n d exer cise a n swer s bef or e you go on t o t omor r ow's l esson .

Quiz 1. Wh a t do t h e f ol l owin g pa t t er n s ma t ch ? a . /a|bc*/ b. /[\d]{1,3}/ c. /\bc[aou]t\b/ d. /(xy+z)\.\1/ e. /^$/ 2. Wr it e pa t t er n s t h a t ma t ch t h e f ol l owin g: a . Five or mor e l ower ca se l et t er s (a -z ). b. Eit h er t h e n u mber 1 or t h e st r in g one. c. st r in g of digit s opt ion a l l y con t a in in g a decima l poin t . d. An y l et t er , f ol l owed by a n y vowel , f ol l owed by t h e sa me l et t er a ga in . e. On e or mor e + ch a r a ct er s. 3. Su ppose t h e va r ia bl e $var h a s t h e va l u e abc123. In dica t e wh et h er t h e f ol l owin g con dit ion a l expr ession s r et u r n t r u e or f a l se. a . $var =~ /./ b. c. d. e. f.

$var $var $var $var $var

=~ =~ =~ =~ =~

/[A-Z]*/ /\w{4-6}/ /(\d)2(\1)/ /abc$/ /1234?/ 4. Su ppose t h e va r ia bl e $var h a s t h e va l u e abc123abc. Wh a t is t h e va l u e of $var

a f t er t h e f ol l owin g su bst it u t ion s? a. b. c. d. e.

$var $var $var $var $var

=~ =~ =~ =~ =~

s/abc/def/; s/[a-z]+/X/g; s/B/W/i; s/(.)\d.*\1/d/; s/(\d+)/$1*2/e; 5. Su ppose t h e va r ia bl e $var h a s t h e va l u e abc123abc. Wh a t is t h e va l u e of $var

a f t er t h e f ol l owin g t r a n sl a t ion s? a . $var =~ tr/a-z/A-Z/; b. $var =~ tr/123/456/; c. $var =~ tr/231/564/; d. $var =~ tr/123/ /s; e. $var =~ tr/123//cd;

Exercises 1. Wr it e a pr ogr a m t h a t r ea ds a l l t h e in pu t f r om t h e st a n da r d in pu t f il e, con ver t s a l l t h e vowel s (except y) t o u pper ca se, a n d pr in t s t h e r esu l t on t h e st a n da r d ou t pu t f il e. 2. Wr it e a pr ogr a m t h a t cou n t s t h e n u mber of t imes ea ch digit a ppea r s in t h e

st a n da r d in pu t f il e. Pr in t t h e t ot a l f or ea ch digit a n d t h e su m of a l l t h e t ot a l s. 3. Wr it e a pr ogr a m t h a t r ever ses t h e or der of t h e f ir st t h r ee wor ds of ea ch in pu t l in e (f r om t h e st a n da r d in pu t f il e) u sin g t h e su bst it u t ion oper a t or . Lea ve t h e spa cin g u n ch a n ged, a n d pr in t ea ch r esu l t in g l in e. 4. Wr it e a pr ogr a m t h a t a dds 1 t o ever y n u mber in t h e st a n da r d in pu t f il e. Pr in t t h e r esu l t s. 5. BUG BUSTER: Wh a t is wr on g wit h t h e f ol l owin g pr ogr a m? #!/usr/local/bin/perl while # put $line print }

($line = ) { quotes around each line of input =~ /^.*$/"\1"/; ($line);

6. BUG BUSTER: Wh a t is wr on g wit h t h e f ol l owin g pr ogr a m? #!/usr/local/bin/perl while ($line = ) { if ($line =~ /[\d]*/) { print ("This line contains the digits '$&'\n"); } }

We e k 1 Week 1 in Review

By n ow, you kn ow en ou gh a bou t pr ogr a mmin g in Per l t o wr it e pr ogr a ms t h a t per f or m ma n y u sef u l t a sks. Th e pr ogr a m in List in g R1.1, wh ich t a kes a n u mber a n d pr in t s ou t it s En gl ish equ iva l en t , il l u st r a t es some of t h e con cept s you 've l ea r n ed du r in g you r f ir st week.

List ing R1.1. Pr int ing t he Eng l ish e quival e nt o f nume r ic input . 1:

#!/usr/local/bin/perl

2: 3:

# define the strings used in printing

4:

@digitword = ("", "one", "two", "three", "four", "five",

5: 6: 7:

"six", "seven", "eight", "nine"); @digit10word = ("", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety");

8:

@teenword = ("ten", "eleven", "twelve", "thirteen", "fourteen",

9:

"fifteen", "sixteen", "seventeen", "eighteen", "nineteen");

10: @groupword = ("", "thousand", "million", "billion", "trillion", 11:

"quadrillion", "quintillion", "sextillion", "septillion",

12:

"octillion", "novillion", "decillion");

13: 14: # read a line of input and remove all blanks, commas and tabs;

15: # complain about anything else 16: $inputline = ; 17: chop ($inputline); 18: $inputline =~ s/[, \t]+//g; 19: if ($inputline =~ /[^\d]/) { 20:

die ("Input must be a number.\n");

21: } 22: 23: # remove leading zeroes 24: $inputline =~ s/^0+//; 25: $inputline =~ s/^$/0/;

# put one back if they're all zero

26: 27: # split into digits: $grouping contains the number of groups 28: # of digits, and $oddlot contains the number of digits in the 29: # first group, which may be only 1 or 2 (e.g., the 1 in 1,000) 30: @digits = split(//, $inputline); 31: if (@digits > 36) { 32:

die ("Number too large for program to handle.\n");

33: } 34: $oddlot = @digits % 3; 35: $grouping = (@digits-1) / 3; 36: 37: # this loop iterates once for each grouping 38: $count = 0; 39: while ($grouping >= 0) { 40:

if ($oddlot == 2) {

41:

$digit1 = 0;

42:

$digit2 = $digits[0];

43:

$digit3 = $digits[1];

44: 45:

$count += 2; } elsif ($oddlot == 1) {

46:

$digit1 = 0;

47:

$digit2 = 0;

48:

$digits = $digits[0];

49:

$count += 1;

50:

} else {

# regular group of three digits

51:

$digit1 = $digits[$count];

52:

$digit2 = $digits[$count+1];

53:

$digit3 = $digits[$count+2];

54:

$count += 3;

55:

}

56:

$oddlot = 0;

57:

if ($digit1 != 0) {

58:

print ("$digitword[$digit1] hundred ");

59:

}

60:

if (($digit1 != 0 || ($grouping == 0 && $count > 3)) &&

61:

($digit2 != 0 || $digit3 != 0)) {

62:

print ("and ");

63:

}

64:

if ($digit2 == 1) {

65: 66:

print ("$teenword[$digit3] "); } elsif ($digit2 != 0 && $digit3 != 0) {

67: "); 68:

print ("$digit10word[$digit2]-$digitword[$digit3]

} elsif ($digit2 != 0 || $digit3 != 0) {

69: ");

print ("$digit10word[$digit2]$digitword[$digit3]

70:

}

71:

if ($digit1 != 0 || $digit2 != 0 || $digit3 != 0) {

72:

print ("$groupword[$grouping]\n");

73:

} elsif ($count 10);

3. How ma n y t imes does t h e f ol l owin g l oop it er a t e? for ($count = 1; $count >>

Righ t -ju st if ied ou t pu t

@|||

Cen t er ed ou t pu t

@##.##

Fixed-pr ecision n u mer ic

@*

Mu l t il in e t ext

In left-justified ou t pu t , t h e va l u e bein g displ a yed a ppea r s a t t h e l ef t en d of t h e va l u e f iel d. In right-justified ou t pu t , t h e va l u e bein g displ a yed a ppea r s a t t h e r igh t en d of t h e va l u e f iel d

In ea ch of t h e f iel d f or ma t s, t h e f ir st ch a r a ct er is a line-fill character. It in dica t es wh et h er t ext f or ma t t in g is r equ ir ed. If t h e @ ch a r a ct er is specif ied a s t h e l in e f il l ch a r a ct er , t ext f or ma t t in g is n ot per f or med. (For a discu ssion of t ext f or ma t t in g, see t h e sect ion t it l ed "For ma t t in g Lon g Ch a r a ct er St r in gs," l a t er t oda y.) In a l l ca ses, except f or t h e mu l t il in e va l u e f iel d @*, t h e widt h of t h e f iel d is equ a l t o t h e n u mber of ch a r a ct er s specif ied. Th e @ ch a r a ct er is in cl u ded wh en cou n t in g t h e n u mber of ch a r a ct er s in t h e va l u e f iel d. For exa mpl e, t h e f ol l owin g f iel d is f ive ch a r a ct er s wide-on e @ ch a r a ct er a n d f ou r > ch a r a ct er s:

@>>>>

Simil a r l y, t h e f ol l owin g f iel d is seven ch a r a ct er s wide-f ou r bef or e t h e decima l poin t , t wo a f t er t h e decima l poin t , a n d t h e decima l poin t it sel f : @###.##

List in g 11.4 il l u st r a t es h ow you ca n u se t h e va l u e f iel d f or ma t s t o pr odu ce a n ea t l y pr in t ed r epor t . Th e r epor t is r edir ect ed t o a f il e f or l a t er pr in t in g.

List ing 11.4. A pr o g r am t hat use s t he var io us val ue -f ie l d f o r mat s. 1:

#!/usr/local/bin/perl

2: 3:

$company = ;

4:

$~ = "COMPANY";

5:

write;

6:

7:

$grandtotal = 0;

8:

$custline = ;

9:

while ($custline ne "") {

10:

$total = 0;

11:

($customer, $date) = split(/#/, $custline);

12:

$~ = "CUSTOMER";

13:

write;

14:

while (1) {

15:

$orderline = ;

16:

if ($orderline eq "" || $orderline =~ /#/) {

17:

$custline = $orderline;

18:

last;

19:

}

20:

($item, $cost) = split(/:/, $orderline);

21:

$~ = "ORDERLINE";

22:

write;

23:

$total += $cost;

24:

}

25:

&write_total ("Total:", $total);

26:

$grandtotal += $total;

27: } 28: &write_total ("Grand total:", $grandtotal); 29: 30: sub write_total { 31:

local ($totalstring, $total) = @_;

32:

$~ = "TOTAL";

33:

write;

34: } 35:

36: format COMPANY = 37: ************* @|||||||||||||||||||||||||||||| ************* 38: $company 39: . 40: format CUSTOMER = 41: @{'Name'}\n"; print "x=$mug->{'x'}\n"; print "y=$mug->{'y'}\n";

Methods A method in a Pe r l c l ass is simpl y a Pe r l subr o ut ine . Pe r l do e sn't pr o vide any spe c ial synt ax f o r me t ho d de f init io n. A me t ho d e xpe c t s it s f ir st ar g ume nt t o be t he o bj e c t o r pac kag e o n whic h it is invo ke d. Pe r l has t wo t ype s o f me t ho ds: st at ic and vir t ual . A static me t ho d e xpe c t s a c l ass name as t he f ir st ar g ume nt . A virtual me t ho d e xpe c t s a r e f e r e nc e t o an o bj e c t as t he f ir st ar g ume nt . The way e ac h me t ho d handl e s t he f ir st ar g ume nt de t e r mine s whe t he r t he me t ho d is st at ic o r vir t ual . A st at ic me t ho d appl ie s f unc t io nal it y t o t he e nt ir e c l ass as a who l e be c ause it use s t he name o f t he c l ass. Func t io nal it y in st at ic me t ho ds is t he r e f o r e appl ic abl e t o al l o bj e c t s o f t he c l ass. Ge ne r al l y, st at ic me t ho ds ig no r e t he f ir st ar g ume nt be c ause t he y al r e ady kno w whic h c l ass t he y ar e in. Co nst r uc t o r s ar e st at ic me t ho ds. A vir t ual me t ho d e xpe c t s a r e f e r e nc e t o an o bj e c t as it s f ir st ar g ume nt . Typic al l y, t he f ir st t hing a vir t ual me t ho d do e s is shif t t he f ir st ar g ume nt int o a self o r this var iabl e and t he n use t hat shif t e d val ue as an o r dinar y r e f e r e nc e . Fo r e xampl e , c o nside r t he f o l l o wing c o de : 1. sub nameLister { 2.

my $this = shift;

3.

my ($keys ,$value );

4.

while (($key, $value) = each (%$this)) {

5.

print "\t$key is $value.\n";

6.

}

7. }

Line 2 in t he l ist ing is whe r e t he $this var iabl e is se t t o po int t o t he o bj e c t . In l ine 4, t he $this ar r ay is de -r e f e r e nc e d at e ve r y $key l o c at io n. TIP Look a t t h e .pm f il es in t h e Per l dist r ibu t ion f or sa mpl e code t h a t wil l sh ow you h ow met h ods a r e decl a r ed a n d u sed.

Exporting Methods If yo u t r ie d t o invo ke t he Cocoa.pm pac kag e r ig ht no w, yo u'd g e t an e r r o r me ssag e f r o m Pe r l at c o mpil e t ime abo ut t he me t ho ds no t be ing f o und. This e r r o r o c c ur s be c ause t he Cocoa.pm me t ho ds have no t be e n e xpo r t e d. To e xpo r t t he se f unc t io ns, yo u ne e d t he Expo r t e r mo dul e . Add t he f o l l o wing l ine s t o t he be g inning o f c o de in t he pac kag e : require Exporter; @ISA = qw(Exporter);

The se t wo l ine s f o r c e t he inc l usio n o f t he Exporter.pm mo dul e and t he n se t t he @ISA ar r ay wit h t he name o f t he Expo r t e r c l ass t o l o o k f o r . To e xpo r t yo ur o wn c l ass's me t ho ds, yo u l ist t he m in t he @EXPORT ar r ay. Fo r e xampl e , t o e xpo r t t he closeMain and declareMain me t ho ds, yo u use t he f o l l o wing st at e me nt : @EXPORT(declareMain, closeMain);

Inhe r it anc e in a Pe r l c l ass is t hr o ug h t he @ISA ar r ay. The @ISA ar r ay do e s no t have t o be de f ine d in e ve r y pac kag e ; ho we ve r , whe n it is de f ine d, Pe r l t r e at s it as a spe c ial ar r ay o f dir e c t o r y name s. This ar r ay is simil ar t o t he @INC ar r ay, whe r e dir e c t o r ie s ar e se ar c he d f o r f il e s t o inc l ude . The @ISA ar r ay c o nt ains t he name s o f t he c l asse s (pac kag e s) t o l o o k f o r me t ho ds in o t he r c l asse s in if a me t ho d in t he c ur r e nt pac kag e is no t f o und. The @ISA ar r ay c o nt ains t he name s o f t he base c l asse s f r o m whic h t he c ur r e nt c l ass inhe r it s. The se ar c h is do ne in t he o r de r t hat t he c l asse s ar e l ist e d in t he @ISA ar r ays. Al l me t ho ds c al l e d by a c l ass must be l o ng t o t he same c l ass o r t he base c l asse s de f ine d in t he @ISA ar r ay. If a me t ho d isn't f o und in t he @ISA ar r ay, Pe r l l o o ks f o r an AUTOLOAD() r o ut ine . This o pt io nal r o ut ine is de f ine d as sub in t he c ur r e nt pac kag e . To use t he AUTOLOAD f unc t io n, yo u c al l t he autoload.pm pac kag e wit h t he use Autoload; st at e me nt . The AUTOLOAD f unc t io n t r ie s t o l o ad t he c al l e d f unc t io n f r o m t he inst al l e d Pe r l l ibr ar ie s. If t he AUTOLOAD c al l al so f ail s, Pe r l make s o ne f inal t r y at t he UNIVERSAL c l ass, whic h is t he c at c h-al l f o r al l me t ho ds no t de f ine d e l se whe r e . Pe r l g e ne r at e s an e r r o r abo ut unr e so l ve d f unc t io ns if t his st e p al so f ail s.

Invoking Methods

The r e ar e t wo ways t o invo ke a me t ho d f o r an o bj e c t : by making a r e f e r e nc e t o an o bj e c t (vir t ual ) o r e xpl ic it l y r e f e r r ing t o t he c l ass name (st at ic ). Yo u have t o e xpo r t a me t ho d t o be abl e t o c al l it . Add a f e w mo r e me t ho ds t o t he Cocoa c l ass t o g e t t he f il e t o r e se mbl e t he f o l l o wing c o de : package Cocoa; require Exporter;

@ISA = qw(Exporter); @EXPORT = qw(setImports, declareMain, closeMain);

# # This routine creates the references for imports in Java functions # sub setImports{ my $class = shift @_; my @names = @_;

foreach (@names) { print "import " .

$_ . ";\n";

} }

# # This routine declares the main function in a Java script # sub declareMain{ my $class = shift @_; my ( $name, $extends, $implements) = @_;

print "\n public class $name";

if ($extends) { print " extends " . $extends; } if ($implements) { print " implements " . $implements; } print " { \n"; }

# # This routine declares the main function in a Java script # sub closeMain{ print "} \n"; }

# #

This subroutine creates the header for the file.

# sub new { my $this = {}; print "\n /* \n ** Created by Cocoa.pm \n ** Use at own risk \n */ \n"; bless $this; return $this; }

1;

No w, wr it e a simpl e Pe r l sc r ipt t o use t he me t ho ds f o r t his c l ass. Be c ause yo u c an

o nl y st ar t and c l o se t he he ade r , e xamine t he f o l l o wing c o de f o r a sc r ipt t o c r e at e a ske l e t o n Java appl e t so ur c e : #!/usr/bin/perl

use Cocoa;

$cup = new Cocoa;

$cup->setImports( 'java.io.InputStream', 'java.net.*'); $cup->declareMain( "Msg" , "java.applet.Applet", "Runnable"); $cup->closeMain();

This sc r ipt g e ne r at e s c o de f o r a Java appl e t c al l e d Msg t hat e xt e nds t he java.applet.Applet appl e t and impl e me nt s f unc t io ns t hat ar e r unnabl e . Yo u c al l t he f unc t io n wit h t he $cup->... c al l . The f o l l o wing t hr e e l ine s o f c o de :

$cup->setImports( 'java.io.InputStream', 'java.net.*');3 $cup->declareMain( "Msg" , "java.applet.Applet", "Runnable"); $cup->closeMain();

c o ul d be r e wr it t e n as f unc t io ns: Cocoa::setImports($cup,

'java.io.InputStream', 'java.net.*');

Cocoa::declareMain($cup, "Msg" , "java.applet.Applet", "Runnable"); Cocoa::closeMain($cup);

This t ype o f e quival e nc e was sho wn in t he se c t io n "Bl e ssing a Co nst r uc t o r ," e ar l ie r t o day. In bo t h c ase s, t he f ir st par ame t e r is t he r e f e r e nc e t o t he o bj e c t it se l f . Running t he t e st sc r ipt sho wn g e ne r at e s t he f o l l o wing o ut put : /* ** Created by Cocoa.pm

** Use at own risk */ import java.io.InputStream; import java.net.*;

public class Msg extends java.applet.Applet implements Runnable { }

An impo r t ant no t e abo ut c al l ing t he me t ho ds: If yo u have any ar g ume nt s in a me t ho d, use par e nt he se s if yo u ar e using t he -> (al so kno wn as indir e c t ) me t ho d. The par e nt he se s ar e r e quir e d t o inc l ude al l t he ar g ume nt s wit h t he f o l l o wing st at e me nt : $cup->setImports( 'java.io.InputStream', 'java.net.*');

Ho we ve r , t he f o l l o wing st at e me nt : Cocoa::setImports($cup,

'java.io.InputStream', 'java.net.*');

c an al so be r e wr it t e n wit ho ut par e nt he se s as t his: Cocoa::setImports $cup,

'java.io.InputStream', 'java.net.*' ;

The c ho ic e is yo ur s abo ut ho w yo u make yo ur c o de r e adabl e t o o t he r pr o g r amme r s. Use par e nt he se s if yo u f e e l t hat it wil l make t he c o de mo r e r e adabl e .

Overrides So me t ime s yo u want t o spe c if y whic h c l ass's me t ho d t o use , suc h as whe n t he same name d me t ho d is spe c if ie d in t wo dif f e r e nt c l asse s. Fo r e xampl e , if t he f unc t io n grind is de f ine d in bo t h Espresso and Qava c l asse s, yo u c an spe c if y whic h c l ass's f unc t io n t o use by using t he :: o pe r at o r . The f o l l o wing c al l s wo ul d use t he c al l in Espresso:

$mess = Espresso::grind("whole","lotta","bags");

Espresso::grind($mess, "whole","lotta","bags");

The f o l l o wing c al l s wo ul d use t he grind() f unc t io n in t he Qava c l ass:

$mess = Qava::grind("whole","lotta","bags"); Qava::grind($mess, "whole","lotta","bags");

Yo u mig ht want t o c al l a me t ho d base d o n so me ac t io n t hat t he pr o g r am yo u ar e wr it ing has al r e ady t ake n. In o t he r wo r ds, yo u want t o use t he Qava me t ho d f o r a c e r t ain c o ndit io n and t he Espresso me t ho d f o r ano t he r . In t his c ase , yo u c an use symbo l ic r e f e r e nc e s t o make t he c al l t o t he r e quir e d f unc t io n, as in t he f o l l o wing e xampl e : $method = $local ? "Qava::" : "Espresso::"; $cup->{$method}grind(@args);

Destructors Pe r l t r ac ks t he numbe r o f l inks t o o bj e c t s. Whe n t he l ast r e f e r e nc e t o an o bj e c t is f r e e d t o t he me mo r y po o l , t he o bj e c t is aut o mat ic al l y de st r o ye d. This de st r uc t io n o f t he o bj e c t c o ul d o c c ur af t e r yo ur c o de st o ps and t he sc r ipt is abo ut t o e xit . Fo r g l o bal var iabl e s, t he de st r uc t io n happe ns af t e r t he l ast l ine in yo ur c o de e xe c ut e s. If yo u want t o c apt ur e c o nt r o l j ust be f o r e t he o bj e c t is f r e e d, yo u c an de f ine a DESTROY() me t ho d in yo ur c l ass. No t e t he use o f al l c apit al l e t t e r s in t he name . The DESTROY() me t ho d is c al l e d j ust be f o r e t he o bj e c t is r e l e ase d, whic h e nabl e s yo u t o do any ne c e ssar y c l e anup. The DESTROY() f unc t io n do e s no t c al l o t he r DESTROY() f unc t io ns aut o mat ic al l y; Pe r l do e sn't do ne st e d de st r uc t io n f o r yo u. If yo ur c o nst r uc t o r r e -bl e sse d a r e f e r e nc e f r o m o ne o f yo ur base c l asse s, yo ur DESTROY() mig ht ne e d t o c al l DESTROY() f o r any base c l asse s. Al l o bj e c t r e f e r e nc e s t hat ar e c o nt aine d in a g ive n o bj e c t ar e f r e e d and de st r o ye d aut o mat ic al l y whe n t he c ur r e nt o bj e c t is f r e e d. Usual l y, yo u do no t have t o de f ine a DESTROY f unc t io n, but whe n yo u do ne e d it , it t ake s t he f o l l o wing f o r m: sub DESTROY {

# # Add code here. # }

Fo r mo st pur po se s, Pe r l use s a simpl e , r e f e r e nc e -base d g ar bag e c o l l e c t io n syst e m. The numbe r o f r e f e r e nc e s t o any g ive n o bj e c t at t he t ime o f g ar bag e c o l l e c t io n must be g r e at e r t han ze r o , o r t he me mo r y f o r t hat o bj e c t is f r e e d. Whe n yo ur pr o g r am e xit s, an e xhaust ive se ar c h-and-de st r o y f unc t io n in Pe r l do e s g ar bag e c o l l e c t io n. Eve r yt hing in t he pr o c e ss is summar il y de l e t e d. In UNIX o r UNIX-l ike syst e ms, t his mig ht se e m l ike a wast e , but it 's ac t ual l y quit e ne c e ssar y t o pe r f o r m in e mbe dde d syst e ms o r in a mul t it hr e ade d e nvir o nme nt .

Inheritance Me t ho ds in c l asse s ar e inhe r it e d wit h t he pat hs in t he @ISA ar r ay. Var iabl e s must be se t up e xpl ic it l y f o r inhe r it anc e . Assume yo u de f ine a ne w c l ass c al l e d Bean.pm t o inc l ude so me o f t he f unc t io nal it y t hat ano t he r c l ass Coffee.pm wil l inhe r it . The e xampl e in t his se c t io n de mo nst r at e s ho w t o inhe r it inst anc e var iabl e s f r o m o ne c l ass (al so r e f e r r e d t o as a "supe r c l ass" o r "base c l ass"). The st e ps in inhe r it anc e r e quir e c al l ing t he supe r c l ass's c o nst r uc t o r and adding o ne 's o wn inst anc e var iabl e s t o t he ne w o bj e c t . In t his e xampl e , t he Coffee c l ass inhe r it s val ue s f r o m t he base c l ass c al l e d Bean. The t wo f il e s ar e c al l e d Coffee.pm and Bean.pm, r e spe c t ive l y. List ing 19.4 is t he c o de f o r Bean.pm.

List ing 19.4. The c o de f o r Bean.pm.

package Bean; require Exporter;

@ISA = qw(Exporter);

@EXPORT = qw(setBeanType);

sub new { my $type = shift; my $this = {}; $this->{'Bean'} = 'Colombian'; bless $this, $type; return $this; }

# # This subroutine sets the class name sub setBeanType{ my ($class, $name) =

@_;

$class->{'Bean'} = $name; print "Set bean to $name \n"; } 1;

List ing 19.4 has no o ut put .

In t his l ist ing , t he $this var iabl e se t s a val ue in t he ano nymo us hash f o r t he 'Bean' t ype t o be 'Colombian'. The setBeanType() me t ho d is al so de c l ar e d so t hat t he 'Bean' t ype c an al so be c hang e d by a pr o g r am. The subr o ut ine f o r r e se t t ing t he val ue o f 'Bean' use s t he $class r e f e r e nc e t o g e t t o t he ano nymo us hash f o r t he o bj e c t . Re me mbe r t hat a r e f e r e nc e t o t his ano nymo us hash c r e at e d t he r e f e r e nc e in t he f ir st pl ac e wit h t he new() f unc t io n. The val ue s in t he Bean c l ass wil l be inhe r it e d by t he Coffee c l ass. The Coffee.pm

f il e is sho wn in List ing 19.5.

List ing 19.5. The Coffee.pm f il e .

1

#

2

# The Coffee.pm file to illustrate inheritance.

3

#

4

package Coffee;

5

require Exporter;

6

require Bean;

7

@ISA = qw(Exporter, Bean);

8

@EXPORT = qw(setImports, declareMain, closeMain);

9

#

10 # set item 11 # 12 sub setCoffeeType{ 13

my ($class,$name) =

14

$class->{'Coffee'} = $name;

15

print "Set coffee type to $name \n";

16

}

17

#

18

#

19

#

20

sub new {

21 22 23

@_;

constructor

my $type my $this

= shift; = Bean->new();

$this->{'Coffee'} = 'Instant';

##### {'Coffee'}. Lo o k at t he new() c o nst r uc t o r f o r t he Coffee c l ass in l ine 20. The $this r e f e r e nc e po int s t o t he ano nymo us hash r e t ur ne d by Bean.pm and no t a hash c r e at e d l o c al l y. In o t he r wo r ds, t he f o l l o wing st at e me nt c r e at e s an e nt ir e l y dif f e r e nt hash t hat has no t hing t o do wit h t he hash c r e at e d in t he Bean.pm c o nst r uc t o r :

my $this = {};

# This is not the way to do it for inheritance.

my $this = $theSuperClass->new();

# this is the way.

List ing 19.6 sho ws ho w t o c al l t he se f unc t io ns.

List ing 19.6. Cal l ing inhe r it e d me t ho ds. 1

#!/usr/bin/perl

2

push (@INC,'pwd');

3

use Coffee;

4

$cup = new Coffee;

5

print "\n -------------------- Initial values ------------ \n";

6

print "Coffee: $cup->{'Coffee'} \n";

7

print "Bean: $cup->{'Bean'} \n";

8

print "\n -------------------- Change Bean Type ---------- \n";

9

$cup->setBeanType('Mixed');

10

print "Bean Type is now $cup->{'Bean'} \n";

11

print "\n ------------------ Change Coffee Type ---------- \n";

12

$cup->setCoffeeType('Instant');

13

print "Type of coffee: $cup->{'Coffee'} \n";

-------------------- Initial values -----------Coffee: Instant Bean: Colombian

-------------------- Change Bean Type ---------Set bean to Mixed Bean Type is now Mixed

------------------ Change Coffee Type ---------Set coffee type to Instant Type of coffee: Instant

The init ial val ue s f o r t he 'Bean' and 'Coffee' indic e s in t he ano nymo us hash f o r t he o bj e c t ar e pr int e d f ir st . The me mbe r f unc t io ns ar e c al l e d t o se t t he val ue s t o dif f e r e nt name s and t he n pr int e d. Me t ho ds c an have se ve r al t ype s o f ar g ume nt s. It 's ho w yo u pr o c e ss t he ar g ume nt s

t hat c o unt s. Fo r e xampl e , yo u c an add t he f o l l o wing me t ho d t o t he Coffee.pm mo dul e : sub makeCup { my ($class, $cream, $sugar, $dope) = @_; print "\n================================== \n"; print "Making a cup \n"; print "Add cream \n" if ($cream); print "Add $sugar sugar cubes\n" if ($sugar); print "Making some really addictive coffee ;-) \n" if ($dope); print "================================== \n"; }

The f unc t io n makeCup() t ake s t hr e e ar g ume nt s but pr o c e sse s t he m o nl y if it se e s t he m. To t e st t his f unc t io nal it y, c o nside r List ing 19.7.

List ing 19.7. Using t he makeCup() f unc t io n.

1

#!/usr/bin/perl

2

push (@INC,'pwd');

3

use Coffee;

4

$cup = new Coffee;

5

#

6

#

7

#

8

print "\n Calling

9

$cup->makeCup;

10

#

11

#

With no parameters

with no parameters: \n";

With one parameter

12

#

13

print "\n Calling

14

$cup->makeCup('1');

15

#

16

#

17

#

18

print "\n Calling

19

$cup->makeCup(1,'2');

20

#

21

#

22

#

23

print "\n Calling

24

$cup->makeCup('1',3,'1');

with one parameter: \n";

With two parameters

with two parameters: \n";

With all three parameters

Calling

with three parameters: \n";

with no parameters:

================================== Making a cup ==================================

Calling

with one parameter:

================================== Making a cup Add cream ==================================

Calling

with two parameters:

================================== Making a cup Add cream Add 2 sugar cubes ==================================

Calling

with three parameters:

================================== Making a cup Add cream Add 3 sugar cubes Making some really addictive coffee ;-) ==================================

Line 9 c al l s t he f unc t io n wit h no par ame t e r s. In l ine 14, t he f unc t io n c al l has o ne par ame t e r . The par ame t e r s ar e passe d e it he r as st r ing s o r int e g e r s, so me t hing t his par t ic ul ar me t ho d do e s no t c ar e abo ut . Lo o k at l ine 19 and l ine 24, whe r e bo t h st r ing s and numbe r s ar e passe d in t he same f unc t io n c al l . Ho we ve r , so me me t ho ds yo u wr it e in t he f ut ur e mig ht r e quir e t his dist inc t io n. In any e ve nt , yo u c an have de f aul t val ue s se t in t he f unc t io n if t he e xpe c t e d par ame t e r is no t passe d. The be havio r o f t he me t ho d c an be dif f e r e nt de pe nding o n t he numbe r o f ar g ume nt s yo u pass it .

Overriding Methods Inhe r it ing f unc t io nal it y f r o m ano t he r c l ass is be ne f ic ial in t hat yo u c an g e t al l t he e xpo r t e d f unc t io nal it y o f t he base c l ass in yo ur ne w c l ass. To se e an e xampl e o f ho w t his wo r ks, add a f unc t io n in t he Bean.pm c l ass c al l e d printType. He r e 's t he subr o ut ine :

sub printType { my $class =

shift @_;

print "The type of Bean is $class->{'Bean'} \n"; }

Do no t f o r g e t t o updat e t he @EXPORT ar r ay by adding t he name o f t he f unc t io n t o e xpo r t . The ne w st at e me nt sho ul d l o o k l ike t his: @EXPORT = qw(setBeanType, printType, printType);

No w c al l t he printType f unc t io n. The ne xt t hr e e l ine s sho w t hr e e ways t o c al l t he f unc t io n: $cup->Coffee::printType(); $cup->printType(); $cup->Bean::printType();

The o ut put f r o m al l t hr e e l ine s is t he same : The type of Bean is Mixed The type of Bean is Mixed The type of Bean is Mixed

Why is t his so ? The r e is no printType() f unc t io n in t he inhe r it ing c l ass, so t he printType() f unc t io n in t he base c l ass is use d inst e ad. Nat ur al l y, if yo u want yo ur o wn c l ass t o have it s o wn printType f unc t io n, yo u have t o de f ine it . In t he Coffee.pm f il e , add t he f o l l o wing l ine s:

# # This routine prints the type of $class->{'Coffee'} #

sub printType { my $class =

shift @_;

print "The type of Coffee is $class->{'Coffee'} \n"; }

Yo u must al so mo dif y t he @EXPORT t o wo r k wit h t his f unc t io n:

@EXPORT = qw(setImports, declareMain, closeMain, printType);

No w t he o ut put f r o m t he t hr e e l ine s l o o ks l ike t his: The type of Coffee is Instant The type of Coffee is Instant The type of Bean is Mixed

The base c l ass f unc t io n is c al l e d o nl y whe n t he Bean:: o ve r r ide is g ive n. In t he o t he r c ase s, o nl y t he inhe r it e d c l ass f unc t io n is c al l e d. What if yo u do no t kno w t he base c l ass name o r e ve n whe r e t he name is de f ine d? In t his c ase , yo u c an use t he SUPER:: pse udo -c l ass r e se r ve d wo r d. Using t he SUPER:: o ve r r ide e nabl e s yo u t o c al l an o ve r r idde n supe r c l ass me t ho d wit ho ut ac t ual l y kno wing whe r e t hat me t ho d is de f ine d. The SUPER:: c o nst r uc t is me aning f ul o nl y wit hin t he c l ass. If yo u'r e t r ying t o c o nt r o l whe r e t he me t ho d se ar c h be g ins and yo u'r e e xe c ut ing in t he c l ass it se l f , yo u c an use t he SUPER:: pse udo c l ass, whic h inst r uc t s Pe r l t o st ar t l o o king in yo ur base c l ass's @ISA l ist wit ho ut e xpl ic it l y naming it :

$this->SUPER::function( ... argument list ... );

Inst e ad o f Bean:: we c an use SUPER::. The c al l t o t he f unc t io n printType() be c o me s

$cup->SUPER::printType();

and t he o ut put is t he f o l l o wing :

The type of Bean is Mixed

A Few Comments About Classes and Objects in Perl One adve r t ise d st r e ng t h o f o bj e c t -o r ie nt e d l ang uag e s is t he e ase wit h whic h ne w c o de c an use o l d c o de . Pac kag e s in Pe r l l e t yo u r e use c o de t hr o ug h t he use o f o bj e c t s and inhe r it anc e . OOP l ang uag e s use dat a e nc apsul at io n t o l e t yo u hide t he inne r wo r king s o f c o mpl ic at e d c o de . Pac kag e s and mo dul e s in Pe r l pr o vide a g r e at de al o f dat a e nc apsul at io n wit h t he use o f t he my c o nst r uc t . Pe r l , ho we ve r , do e s no t g uar ant e e t hat a c l ass inhe r it ing yo ur c o de wil l no t at t e mpt t o ac c e ss yo ur c l ass var iabl e s dir e c t l y, t he r e by e l iminat ing t he advant ag e o f dat a e nc apsul at io n. The y c an if t he y r e al l y want t o ; ho we ve r , t his t ype o f pr o c e dur e is c o nside r e d bad pr ac t ic e , and shame o n yo u if yo u do it .

DO def in e met h ods t o a ccess cl a ss va r ia bl es. DON'T a ccess cl a ss va r ia bl es dir ect l y f r om ou t side t h e modu l e.

Whe n wr it ing a pac kag e , yo u sho ul d e nsur e t hat e ve r yt hing a me t ho d ne e ds is avail abl e t hr o ug h t he o bj e c t o r is passe d as a par ame t e r t o t he me t ho d. Fr o m wit hin t he pac kag e , ac c e ss any g l o bal var iabl e s o nl y t hr o ug h r e f e r e nc e s passe d t hr o ug h me t ho ds. Fo r st at ic o r g l o bal dat a t o be use d by t he me t ho ds, yo u have t o de f ine t he c o nt e xt o f t he dat a in t he base c l ass using t he local() c o nst r uc t . The subc l ass wil l t he n c al l t he base c l ass t o g e t t he dat a f o r it . On o c c asio n, a subc l ass mig ht want t o o ve r r ide t hat dat a and r e pl ac e it wit h ne w dat a. Whe n t his happe ns, t he supe r c l ass mig ht no t kno w ho w t o f ind t he ne w c o py o f t he dat a. In suc h c ase s, it 's be st t o de f ine a r e f e r e nc e t o t he dat a and t he n have al l base c l asse s and subc l asse s mo dif y t he var iabl e t hr o ug h t hat r e f e r e nc e . Final l y, yo u wil l se e r e f e r e nc e s t o o bj e c t s and c l asse s suc h as t he f o l l o wing : use Coffee::Bean;

This c o de is int e r pr e t e d t o me an "Lo o k f o r Bean.pm in t he Coffee subdir e c t o r y in al l t he dir e c t o r ie s in t he @INC ar r ay." If I we r e t o mo ve Bean.pm int o t he ./Coffee

dir e c t o r y, al l t he pr e vio us e xampl e s wo ul d wo r k wit h t he ne w use st at e me nt . The advant ag e t o t his appr o ac h is t hat yo u have o ne subc l ass c l ass f il e in o ne dir e c t o r y and t he base c l ass in a l o we r dir e c t o r y. It he l ps ke e p c o de o r g anize d. To have a st at e me nt l ike t he f o l l o wing : use Another::Sub::Menu;

yo u wo ul d se e a dir e c t o r y sub-t r e e l ike t his: ./Another/Sub/Menu.pm

Summary This c hapt e r pr o vide s a br ie f int r o duc t io n t o o bj e c t -o r ie nt e d pr o g r amming in Pe r l . Pe r l pr o vide s t he OOP f e at ur e s o f dat a e nc apsul at io n and inhe r it anc e using mo dul e s and pac kag e s. A c l ass in Pe r l is simpl y a pac kag e . A pac kag e f o r a c l ass pr o vide s al l t he me t ho ds f o r o bj e c t s c r e at e d f o r t he c l ass. An o bj e c t is simpl y a r e f e r e nc e t o dat a t hat kno ws whic h c l ass it be l o ng s t o . A me t ho d in a c l ass is simpl y a subr o ut ine . The o nl y c at c h abo ut wr it ing suc h me t ho ds is t hat t he name o f t he c l ass is al ways t he f ir st ar g ume nt o f t he me t ho d. The bless() f unc t io n is use d t o t ie a r e f e r e nc e t o a c l ass name . The bless() f unc t io n is c al l e d in t he c o nst r uc t o r f unc t io n new() t o c r e at e an o bj e c t and t he n c o nne c t t he r e f e r e nc e t o t he o bj e c t wit h t he name o f t he c l ass. Wit h inhe r it anc e , t he base c l ass is t he c l ass f r o m whic h me t ho ds (and dat a) ar e inhe r it e d. The base c l ass is al so c al l e d t he supe r c l ass. The c l ass t hat inhe r it s t he se it e ms f r o m t he supe r c l ass is c al l e d t he subc l ass. Mul t ipl e inhe r it anc e is al l o we d in Pe r l . Dat a inhe r it anc e is t he pr o g r amme r 's r e spo nsibil it y and r e quir e s using r e f e r e nc e s. The subc l ass is al l o we d t o kno w t hing s abo ut it s imme diat e supe r c l ass; t he supe r c l ass is no t al l o we d t o kno w anyt hing abo ut a subc l ass.

Q&A Q: A:

What do e s t he bless() f unc t io n do ? Th e bless() f u n ct ion t a kes on e or t wo a r gu men t s. Th e f ir st a r gu men t is a r ef er en ce t o a n object . Th e secon d a r gu men t is opt ion a l a n d specif ies t h e n a me of a cl a ss; if t h e n a me is n ot specif ied, t h e def a u l t is t h e cu r r en t cl a ss. Af t er t h e ca l l , t h e r ef er en ce u ses t h e n a me a s it s cl a ss n a me. As a r esu l t , t h e r ef er en ce becomes a n object of t h e cl a ss wh ose n a me wa s specif ied.

Q: A:

What 's t he dif f e r e nc e be t we e n an o bj e c t and a r e f e r e nc e ? Object s a r e bl essed; r ef er en ces a r e n ot . Object s bel on g t o a cl a ss, bu t r ef er en ces do n ot h a ve t o. What 's t he dif f e r e nc e be t we e n st at ic and vir t ual me t ho ds? St a t ic met h ods expect a cl a ss n a me a s t h e f ir st a r gu men t . Vir t u a l met h ods expect a r ef er en ce t o a n object a s t h e f ir st a r gu men t . St a t ic met h ods a r e cl a ss-wide; vir t u a l met h ods a r e object -specif ic. I j ust adde d a me t ho d t o my c l ass f il e , but it is ne ve r c al l e d! What 's wr o ng ? Ma ke su r e you a r e u sin g t h e require Exporter; st a t emen t a n d t h a t t h e n a me of t h e n ew f u n ct ion is in t h e @EXPORTER a r r a y.

Q: A:

Q: A:

Workshop The Wo r ksho p pr o vide s quiz que st io ns t o he l p yo u so l idif y yo ur unde r st anding o f t he mat e r ial c o ve r e d and e xe r c ise s t o g ive yo u e xpe r ie nc e in using what yo u've l e ar ne d. Tr y and unde r st and t he quiz and e xe r c ise answe r s be f o r e yo u g o o n t o t o mo r r o w's l e sso n.

Quiz 1. Sho w at l e ast t hr e e ways t o c r e at e a ne w o bj e c t o f a g ive n c l ass, Balloon. 2. What 's wr o ng t he f o l l o wing l ine s o f c o de ? { my $x; my $y; $x = \$y; }

3. What ar e t he t hr e e mo st impo r t ant r ul e s abo ut OOP in Pe r l ? 4. Ho w do yo u o ve r r ide a c al l t o a me t ho d t o use t he base c l ass inst e ad o f t he subc l ass?

Exercises 1. Wr it e a simpl e c l ass t o pr int o ut t he day o f t he we e k using t he Ze l l e r s c o ng r ue nc e f o r mul a t o g e t t he day o f t he we e k g ive n a dat e . The f o l l o wing sho ws t he f o r mul a in Pe r l c o de : $zy = $year; $zm = ($month + 10) % 12; $zy- if ($m > 10); $zc = int ( $y / 100 ); $yy = $year % 100; $zeller = ( int ( (26*$zm - 2)/10) + $dayOfMonth + $yy + int($yy/4) + int ($zc/4) - 2* $zc ) % 7;

2. Ext e nd t he c l ass yo u j ust c r e at e d t o al l o w spe c if ying a dat e at c r e at io n

t ime whe r e t he day, mo nt h, ye ar , o r al l t hr e e c an be o pt io nal . Hint : Use t he dat e f unc t io n t o g e t t he c ur r e nt dat e . 3. Cr e at e a c l ass t o l ist t he e nt ir e dir e c t o r y t r e e whe n g ive n a pat h name . 4. Mo dif y t he f o l l o wing f unc t io n t o pr int black if no par ame t e r s ar e passe d t o it :sub make Cup { my ($class, $cream, $sugar, $dope) = @_; print "\n================================== \n"; print "Making a cup \n"; print "Add cream \n" if ($cream); print "Add $sugar sugar cubes\n" if ($sugar); print "Making some really nice coffee ;-) \n" if ($dope); print "================================== \n"; }

Chapter 20 Miscellaneous Features of Perl

CONTENTS ●





● ● ●



● ●



● ● ●

Th e require Fu n ct ion ❍ Th e require Fu n ct ion a n d Su br ou t in e Libr a r ies ❍ Usin g require t o Specif y a Per l Ver sion Th e $#array Va r ia bl es ❍ Con t r ol l in g Ar r a y Len gt h Usin g $#array Al t er n a t ive St r in g Del imit er s ❍ Def in in g St r in gs Usin g file2") || die ("Can't open file2 for writing\n"); # the following only works if file1 isn't too big @contents = ; print OUTFILE (@contents); # we don't really need the call to close, but they # make things a little clearer close (OUTFILE); open (OUTFILE, ">>file2") || die ("Can't append to file2\n"); print OUTFILE (@contents);

4. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl $wordcount = 0; while ($line = ) { # this isn't the best possible pattern to split with, # but it'll do until you've finished Day 7 @words = split(/ /, $line); $wordcount += @words; } open (MESSAGE, "| mail dave") || die ("Can't mail to userid dave.\n"); print MESSAGE ("Total number of words: $wordcount\n"); close (MESSAGE);

5. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl $count = 1; while ($count temp") || die ("Can't open output"); while ($line = ) { print OUTFILE ($line); } close (OUTFILE); exec ("ch13.2a");

3. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

for ($val = 1; $val > 1; vec ($bytes1, $count, 1) = $result; $count-;

} $resultstring = unpack ("b*", $bytes1); $resultstring = $carry . $resultstring if ($carry > 0); print ("$resultstring\n");

2. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl $string1 = ; chop ($string1); $len1 = length ($string1); $string2 = ; chop ($string2); $len2 = length ($string2); if ($len1 % 8 != 0) { $string1 = "0" x (8 - $len1 % 8) . $string1; $len1 += 8 - $len1 % 8; } if ($len2 % 8 != 0) { $string2 = "0" x (8 - $len2 % 8) . $string2; $len2 += 8 - $len2 % 8; } if ($len1 > $len2) { $string2 = "0" x ($len1 - $len2) . $string2; } else { $string1 = "0" x ($len2 - $len1) . $string1; $len1 += ($len2 - $len1); } $bytes1 = pack ("h*", $string1); $bytes2 = pack ("h*", $string2);

$carry = 0; $count = $len1 - 1; while ($count >= 0) { $nybble1 = vec ($bytes1, $count, 4); $nybble2 = vec ($bytes2, $count, 4); $result = ($nybble1 + $nybble2 + $carry) & 15; $carry = ($nybble1 + $nybble2 + $carry) >> 4; vec ($bytes1, $count, 4) = $result; $count-; } $resultstring = unpack ("h*", $bytes1); $resultstring = $carry . $resultstring if ($carry > 0); print ("$resultstring\n");

3. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$value = ; $value *= 100; $value = int ($value + 0.5); $value = sprintf ("%.2f", $value / 100); print ("$value\n");

4. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$passwd = crypt ("bluejays", "ez"); $try = 1; while (1) {

print ("Enter the secret password:\n"); system ("stty -echo"); $guess = ; system ("stty echo"); if (crypt ($guess, substr ($passwd, 0, 2)) eq $passwd) { print ("Correct!\n"); last; } if ($try == 3) { die ("Sorry! Goodbye!\n"); } print ("Try again - "); $try++; }

5. Th is pr ogr a m is a ct u a l l y r ea din g t h e l ow-or der bit of t h e bit vect or . To r ea d t h e h igh -or der bit , u se vec ($packed, 7, 1). 6. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

# This program uses a very dumb sorting algorithm. @list = (41, 26, 11, 9, 8);

# sample list to sort

for ($outer = 0; $outer < @list; $outer++) { for ($inner = 0; $inner < @list; $inner++) { if ($list[$inner] > $list[$inner+1]) { $x = splice (@list, $inner, 1); splice (@list, $inner+1, 0, $x); }

} }

7. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

# assume %oldarray is assigned here while (($subscript, $value) = each (%oldarray)) { if (defined ($newarray{$value})) { print STDERR ("$value already defined\n"); } else { $newarray{$value} = $subscript; } }

8. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

while ($line = ) { @words = split (/\s+/, $line); @shortwords = grep (/^.{1,5}$/, @words); print ("@shortwords\n"); }

9. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$line = ;

$line =~ s/^\s+//; while (1) { last if ($line eq ""); ($word, $line) = split (/\s+/, $line, 2); print ("$word\n"); }

10. Th is su br ou t in e is t r yin g t o r emove a n el emen t f r om a l ist u sin g unshift. Th e su br ou t in e sh ou l d u se shift, n ot unshift.

Answers for Day 15, "System Functions" Quiz 1. Th e a n swer s a r e a s f ol l ows: 1. endpwent, getpwent, getpwnam, getpwuid, a n d setpwent. 2. endhostent, gethostbyaddr, gethostbyname, gethostent, a n d sethostent. 3. endnetent, getnetbyaddr, getnetbyname, getnetent, a n d setnetent. 4. endservent, getservbyname, getservbyport, getservent, a n d setservent. 2. Ser ver pr ocesses ca l l socket, bind, listen, a n d accept, in t h a t or der . Cl ien t pr ocesses ca l l socket, bind, a n d connect, in t h a t or der . 3. Th e a n swer s a r e a s f ol l ows: 1. getpwuid sea r ch es f or a n en t r y in /etc/passwd t h a t ma t ch es a specif ic u ser ID. 2. setprotoent r ewin ds t h e /etc/protocols f il e. 3. gethostbyaddr sea r ch es t h e /etc/hosts f il e f or a pa r t icu l a r n et wor k (In t er n et ) a ddr ess. 4. getgrent r et r ieves t h e n ext en t r y f r om t h e /etc/group f il e. 5. getservbyport sea r ch es t h e /etc/services f il e f or a n en t r y cor r espon din g t o a pa r t icu l a r por t n u mber . 4. To sen d in f or ma t ion u sin g a socket , u se a n ou t pu t f u n ct ion su ch a s print or printf, a n d specif y t h e f il e va r ia bl e a ssocia t ed wit h t h e socket . 5. You ca n obt a in a l l t h e u ser IDs on you r syst em by u sin g getpwent t o r ea d t h e /etc/passwd f il e. Th is f il e con t a in s on e en t r y per u ser ID, a n d t h e u ser ID is pa r t of t h e en t r y.

Exercises 1. Her e is on e possibl e sol u t ion :

#!/usr/local/bin/perl

while (($gname, $password, $groupid, $userids) = getgrent()) { $garray{$gname} = $userids; } foreach $gname (sort keys (%garray)) { print ("Group $gname:\n"); @userids = split (/\s+/, $garray{$gname}); foreach $userid (sort (@userids)) { print ("\t$userid\n"); } }

2. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

while (($name, $d1, $d2, $d3, $d4, $d5, $d6, $homedir) = getpwent()) { $dirlist{$name} = $homedir; } foreach $name (sort keys (%dirlist)) { printf ("userid %-15s has home directory %s\n", $name, $dirlist{$name}); }

3. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

while (@retval = getpwent()) { $retval[8] = "" if ($retval[8] eq ""); $shellarray{$retval[8]} += 1; } foreach $shell (sort count keys (%shellarray)) { printf ("%-25s %5d %s\n", $shell, $shellarray{$shell}, ($shellarray{$shell} == 1 ? "occurrence" : "occurrences")); } sub count { $shellarray{$b} $shellarray{$a}; }

4. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$otherid = fork(); if ($otherid == 0) { # child process $otherid = getppid(); } $| = 1;

# eliminate print buffers

print ("The process id of the other process is $otherid.\n");

5. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$port = 2000;

while (getservbyport($port, "tcp")) { $port++; } ($d1, $d2, $prototype) = getprotobyname ("tcp"); # in the following, replace "silver" with the name # of your machine ($d1, $d2, $d3, $d4, $rawaddr) = gethostbyname ("silver"); $serveraddr = pack ("Sna4x8", 2, $port, $rawaddr); socket (SSOCKET, 2, 1, $prototype) || die ("No socket"); bind (SSOCKET, $serveraddr) || die ("Can't bind"); listen (SSOCKET, 5) || die ("Can't listen"); while (1) { ($clientaddr = accept (SOCKET, SSOCKET)) || die ("Can't accept"); if (fork() == 0) { select (SOCKET); $| = 1; open (MYFILE, "/u/jqpublic/testfile"); while ($line = ) { print SOCKET ($line); } close (MYFILE); close (SOCKET); exit (0); } }

6. getnetent r et u r n s a n a ddr ess a s a n a r r a y of f ou r byt es, n ot a s a r ea da bl e a ddr ess. To con ver t t h e a ddr ess r et u r n ed by getnetent t o r ea da bl e f or m, ca l l unpack.

Answers for Day 16, "Command-Line Options"

Quiz 1. Th e a n swer s a r e a s f ol l ows: 1. Th e -0 opt ion specif ies t h e en d of f il e ch a r a ct er f or t h e in pu t l in e. 2. Th e -s opt ion en a bl es you t o specif y opt ion s f or you r pr ogr a m. 3. Th e -w opt ion t el l s t h e Per l in t er pr et er t o wa r n you if it sees somet h in g t h a t it t h in ks is er r on eou s. 4. Th e -x opt ion t el l s t h e Per l in t er pr et er t h a t you r pr ogr a m is t o be ext r a ct ed f r om a f il e. 5. Th e -n opt ion in dica t es t h a t ea ch l in e of t h e f il es specif ied on t h e comma n d l in e is t o be r ea d. 2. Th e a n swer s a r e a s f ol l ows: 1. Th e in pu t en d-of -l in e ch a r a ct er becomes eit h er n ewl in e or t h e ch a r a ct er specif ied by -l. Th e ou t pu t en d-of -l in e ch a r a ct er becomes eit h er n u l l or t h e ch a r a ct er specif ied by -0. 2. Th e in pu t en d-of -l in e ch a r a ct er becomes eit h er t h e ch a r a ct er specif ied by -l or t h e ch a r a ct er specif ied by -0; if n eit h er opt ion h a s a va l u e su ppl ied wit h it , t h e in pu t l in e ch a r a ct er becomes n u l l . Th e ou t pu t en d-of -l in e ch a r a ct er becomes eit h er n u l l or t h e ch a r a ct er specif ied by -0. 3. Th e -n opt ion t el l s t h e Per l in t er pr et er t o r ea d ea ch l in e of t h e in pu t f il e, bu t does n ot expl icit l y t el l it t o wr it e ou t it s in pu t . Th e -i opt ion copies t h e in pu t f il e t o a t empor a r y f il e, a n d t h en open s t h e in pu t f il e f or wr it in g. If you do n ot expl icit l y wr it e t o t h e f il e you r sel f , n ot h in g get s wr it t en t o it . 4. Th is is a t r ick qu est ion : It doesn 't . You 'l l h a ve t o ma ke su r e t h a t you r Per l commen t s a r e n ot C pr epr ocessor comma n ds. 5. Th e opt ion s f or t h e in t er pr et er a ppea r bef or e t h e Per l pr ogr a m n a me in t h e comma n d l in e, or in t h e h ea der commen t f or t h e pr ogr a m. Th e opt ion s f or t h e pr ogr a m a ppea r a f t er t h e pr ogr a m n a me.

Exercises 1. Her e is on e possibl e sol u t ion : $ perl -i -p -l072 -e ";" testfile Not e t h a t -e ";" in dica t es a n empt y pr ogr a m. (Ot h er wise, t h e Per l in t er pr et er wou l d a ssu me t h a t testfile wa s t h e pr ogr a m, n ot t h e in pu t f il e.)

2. Her e is on e possibl e sol u t ion : $ perl -ne "print if (/\bthe\b/);" file1 file2 ...

3. Her e is on e possibl e sol u t ion : $ perl -nae 'print ("$F[1]\n");' file1 file2 ...

4. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl -s print ("Hello\n") if ($H == 1); print ("Goodbye\n") if ($G == 1);

5. Her e is on e possibl e sol u t ion : $ perl -i -pe "tr/a-z/A-Z/;" file1 file2 ...

6. Th is comma n d l in e wipes ou t a l l of you r in pu t f il es. Use t h e -p opt ion in st ea d of t h e -n opt ion . 7. Th e -i opt ion ca n be specif ied wit h a va l u e (f or cr ea t in g a ba cku p ver sion of t h e f il e). Th e Per l in t er pr et er t h in ks t h a t pe is t h e su f f ix t o a ppen d t o t h e f il en a me, a n d does n ot r ea l iz e t h a t t h ese a r e su pposed t o be opt ion s. (I get t r ipped u p by t h is pr obl em a l l t h e t ime.)

Answers for Day 17, "System Variables" Quiz 1. Th e pa t t er n -ma t ch in g oper a t or , t h e su bst it u t ion oper a t or , t h e t r a n sl a t ion oper a t or , t h e oper a t or (if it a ppea r s in a while or for con dit ion a l expr ession ), t h e chop f u n ct ion , t h e print f u n ct ion , a n d t h e study f u n ct ion . 2. Th e a n swer s a r e a s f ol l ows: 1. Th e $= va r ia bl e con t a in s t h e pa ge l en gt h of a pa r t icu l a r ou t pu t f il e. 2. Th e $/ va r ia bl e con t a in s t h e in pu t en d-of -l in e ch a r a ct er . 3. Th e $? va r ia bl e con t a in s t h e r et u r n code r et u r n ed by a comma n d ca l l ed by t h e system f u n ct ion or en cl osed in ba ck qu ot es. 4. Th e $! va r ia bl e con t a in s t h e er r or code gen er a t ed by a syst em l ibr a r y r ou t in e. 5. Th e @_ va r ia bl e con t a in s t h e l ist of a r gu men t s pa ssed t o a su br ou t in e by t h e ca l l in g pr ogr a m or ca l l in g su br ou t in e. 3. ARGV is t h e f il e va r ia bl e u sed by t h e oper a t or t o r ea d f r om t h e l ist of in pu t f il es specif ied on t h e comma n d l in e. $ARGV is t h e n a me of t h e cu r r en t f il e bein g r ea d by t h e oper a t or . @ARGV is t h e l ist of a r gu men t s (or f il es) specif ied on t h e comma n d l in e. 4. @INC con t a in s t h e dir ect or ies t o sea r ch wh en l ookin g f or f il es t o be in cl u ded. %INC l ist s t h e f il es r equ est ed by t h e require f u n ct ion t h a t h a ve a l r ea dy been f ou n d.

5. $0 is t h e n a me of t h e pr ogr a m you a r e r u n n in g. $1 is def in ed wh en a pa t t er n is ma t ch ed, a n d is t h e f ir st su bpa t t er n en cl osed in pa r en t h eses in t h e ma t ch ed pa t t er n .

Exercises 1. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl -i while () { s/[ \t]+/ /g; tr/A-Z/a-z/; print; }

Al l of t h ese st a t emen t s u se t h e syst em va r ia bl e $_ by def a u l t . 2. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl -i

while ($line = ) { while ($line =~ /

+/g) {

$line = $' . " " . $'; } print ($line); }

3. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl @dirlist = split (/:/, $ENV{"PATH"}); foreach $dir (@dirlist) { print ("$dir\n"); }

Not e t h a t if you r ma ch in e u ses a ch a r a ct er ot h er t h a n : t o sepa r a t e en t r ies in t h e va l u e of you r PATH en vir on men t va r ia bl e, you sh ou l d u se t h is ch a r a ct er in st ea d. 4. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$SIG{"INT"} = stopnum;

$num = 1; while (1) { print ("$num\n"); $num++; }

sub stopnum { print ("\nInterrupted.\n"); exit (0); }

5. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

$total = 0; while ($line = ) { @nums = split (/\s+/, $line); foreach $num (@nums) { $total += $num; } } print ("The total is $total.\n"); __END__ 4 17

26

11 9

5

6. Th e su bst it u t ion oper a t or ma t ch es a pa t t er n , so it over wr it es t h e va l u e of $'. To f ix t h is, copy $' in t o a sca l a r va r ia bl e of you r own bef or e sea r ch in g f or ext r a spa ces.

Answers for Day 18, "References in Perl 5" Quiz 1. Th e cor r ect wa y t o wr it e t h is is $pointer->{$i}. You a r e der ef er en cin g mor e t h a n on ce in t h e l in e sh own in t h e qu est ion . 2. Ma ke t h e l in e my($a,$b)

l ook l ike t h is: my (\$a,\$b) Th en u se @$a a n d @$b t o a ccess t h ese a r r a ys by r ef er en ce. 3. Th er e is n o dif f er en ce a s f a r a s a ccessin g t h e va r ia bl e in $i is con cer n ed. 4. Th e wor d Help. 5. Th e ${variable} ca n be u sed t o cr ea t e symbol ic r ef er en ces. Th e t h r ee l in es cou l d be r ewr it t en by el imin a t in g ${} con st r u ct s a n d u sin g t h e va l u es in st ea d.

Exercises 1. Her e is on e possibl e sol u t ion : $p1 = @a; $p2 = %a; $p3 = sub { return @_ ; }; printf "\n Array reference = $p1"; printf "\n Hash reference = $p2"; printf "\n Subroutine reference = $p3";

2. Use t h e code in t h e given h in t t o con st r u ct you r f u n ct ion wit h on e except ion : you u se a n a r r a y f or @list. Th en you ca n ca l l ea ch f u n ct ion by u sin g t h e in dex in t h e @list:

&$list[$index]();

3. Ha r d l in ks a r e ma in t a in ed by Per l a n d h a ve t o be gr ea t er t h a n z er o f or a va r ia bl e t o exist . Sof t l in ks ca n poin t t o n ot h in g a n d a r e cr ea t ed by a u ser pr ogr a m. 4. Add t h e f ol l owin g l in es t o t h e en d of t h e code: printf "\n Address = $this, $that"; printf "\n Difference of Address = %f \n" $this - $that";

Th e a ddr esses a r e n ot dif f er en t beca u se t h ey poin t t o t h e sa me f u n ct ion .

Answers for Day 19, "Object-Oriented Programming in Perl" Quiz 1. Th e f ol l owin g is cor r ect : Balloon::new(); Balloon->new(); new Balloon;

2. Th is ca u ses a memor y l ea k. Th e memor y a l l oca t ed f or $y h a s a n ext r a r ef er en ce. Th e r ef er en ce cou n t f or $y is set wh en $x is set t o it . Af t er t h e bl ock of code en ds, t h e $y r ef er en ce cou n t r ema in s n on z er o. As a r esu l t , t h e memor y $y h a n gs a r ou n d u n t il t h e pr ogr a m exit s. 3. A cl a ss is on l y a pa cka ge t h a t pr ovides met h ods, a n object is a r ef er en ce, a n d a met h od is a su br ou t in e wit h t h e f ir st a r gu men t a s t h e n a me of t h e cl a ss. 4. Use BaseClassName:: expl icit l y in f r on t of t h e f u n ct ion n a me t o f or ce Per l t o u se t h e ba se cl a ss.

Exercises 1. Cr ea t e a f il e ca l l ed Zeller.pm l ike t h is:

package Zeller;

require Exporter; @EXPORT = (Zeller);

sub Zeller { my ($month,$day,$year) = @_; > }

1;

2. Th en u se t h e f il e in you r Per l scr ipt l ike t h is:

use Zeller;

$z = Zeller(7,21,1962); print "\n Day of the week = $z";

3. Ch eck if t h e n u mber of in comin g pa r a met er s is n ot t h r ee. Use t h e ca l l t o 'date +\%D'. Th e a n swer wil l r et u r n in mm/dd/yy f or ma t . Spl it t h e r espon se on '/' t o get t h e mon t h . $count = scalar (@_); if ($count != 3) { $dt = 'date +\%D'; ($month,$day,$year) = split($_,'/'); else { my ($month,$day,$year) = @_; } $z =

Zeller($month,$day,$year);

4. Her e is on e possibl e sol u t ion : #!/usr/bin/perl print 'find . -depth -print ';

5. Add t h e f ol l owin g l in es of code t o t h e begin n in g of t h e f u n ct ion : if (scalar(@_) == 0)

{

print "\n ================================= \n"; print " Making a black cup of coffee. "; print "\n ================================= \n"; return; }

Answers for Day 20, "Miscellaneous Features of Perl" Quiz 1. Th e a n swer s a r e a s f ol l ows: 1. __LINE__ con t a in s t h e cu r r en t l in e n u mber of t h e execu t in g pr ogr a m or su br ou t in e. 2. __FILE__ con t a in s t h e cu r r en t f il e bein g execu t ed. 3. __END__ in dica t es t h e en d of t h e Per l pr ogr a m. 2. Th e a n swer s a r e a s f ol l ows: 1. It's time to say $var 2. "It's time to say hello"; (in cl u din g t h e qu ot es a n d t h e semicol on ) 3. hello 3. ("one", "two", "three", "", "five") 4. Th er e a r e t wo wa ys: ❍ Wit h t h e #include pr epr ocessor comma n d. ❍ Addin g t h e f il e's dir ect or y t o @INC a n d t h en pa ssin g t h e f il en a me t o require.

Exercises 1. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

@filelist = ; foreach $file (sort (@filelist)) { print ("$file\n"); }

2. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

unshift (@INC, "/u/jqpublic/perlfiles"); require ("sum.pl"); @numlist = ; chop (@numlist);

$total = &sum (@numlist); print ("The total is $total.\n");

3. Her e is on e possibl e sol u t ion : #!/usr/local/bin/perl

package pack1; $var = ; chop ($var); package pack2; $var = ; chop ($var); package main; $total = $pack1'var + $pack2'var; print ("The total is $total.\n");

4. In t h is ca se, is t r ea t ed a s a sca l a r va r ia bl e con t a in in g t h e n a me of a f il e va r ia bl e, n ot a s a sca l a r va r ia bl e con t a in in g a f il e l ist pa t t er n . (To obt a in t h e l a t t er , u se .) 5. Th er e sh ou l d be n o spa ce bet ween t h e