P. 1


|Views: 0|Likes:
Published by Yashjit

More info:

Published by: Yashjit on Dec 02, 2010
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less






  • 1 The Impatient Introduction to Perl
  • 1.1 The history of perl in 100 words or less
  • 1.2 Basic Formatting for this Document
  • 1.3 Do You Have Perl Installed
  • 1.4 Your First Perl Script, EVER
  • 1.5 Default Script Header
  • 1.6 Free Reference Material
  • 1.7 Cheap Reference Material
  • 1.8 Acronyms and Terms
  • 2 Storage
  • 2.1 Scalars
  • 2.1.1 Scalar Strings
  • String Literals
  • Single quotes versus Double quotes
  • chomp
  • concatenation
  • repetition
  • length
  • substr
  • split
  • join
  • qw
  • Multi-Line Strings, HERE Documents
  • 2.1.2 Scalar Numbers
  • Numeric Literals
  • Numeric Functions
  • abs
  • int
  • trigonometry (sin,cos)
  • exponentiation
  • sqrt
  • natural logarithms(exp,log)
  • random numbers (rand, srand)
  • 2.1.3 Converting Between Strings and Numbers
  • Stringify
  • sprintf
  • Numify
  • oct
  • hex
  • Base Conversion Overview
  • 2.1.4 Undefined and Uninitialized Scalars
  • 2.1.5 Booleans
  • TRUE
  • Comparators
  • Logical Operators
  • Default Values
  • Flow Control
  • Precedence
  • Assignment Precedence
  • Flow Control Precedence
  • Conditional Operator
  • 2.1.6 References
  • 2.1.7 Filehandles
  • 2.1.8 Scalar Review
  • 2.2 Arrays
  • 2.2.1 scalar (@array)
  • 2.2.2 push(@array, LIST)
  • 2.2.3 pop(@array)
  • 2.2.4 shift(@array)
  • 2.2.5 unshift( @array, LIST)
  • 2.2.6 foreach (@array)
  • 2.2.7 sort(@array)
  • 2.2.8 reverse(@array)
  • 2.2.9 splice(@array)
  • 2.2.10 Undefined and Uninitialized Arrays
  • 2.3 Hashes
  • 2.3.1 exists ( $hash{$key} )
  • 2.3.2 delete ( $hash{key} )
  • 2.3.3 keys( %hash )
  • 2.3.4 values( %hash )
  • 2.3.5 each( %hash )
  • 2.4 List Context
  • 2.5 References
  • 2.5.1 Named Referents
  • 2.5.2 References to Named Referents
  • 2.5.3 Dereferencing
  • 2.5.4 Anonymous Referents
  • 2.5.5 Complex Data Structures
  • Autovivification
  • Multidimensional Arrays
  • Deep Cloning, Deep Copy
  • Data Persistence
  • 2.5.6 Stringification of References
  • 2.5.7 The ref() function
  • 3 Control Flow
  • 3.1 Labels
  • 3.2 last LABEL;
  • 3.3 next LABEL;
  • 3.4 redo LABEL;
  • 4 Packages and Namespaces and Lexical Scoping
  • 4.1 Package Declaration
  • 4.2 Declaring Package Variables With our
  • 4.3 Package Variables inside a Lexical Scope
  • 4.4 Lexical Scope
  • 4.5 Lexical Variables
  • 4.6 Garbage Collection
  • 4.6.1 Reference Count Garbage Collection
  • 4.6.2 Garbage Collection and Subroutines
  • 4.7 Package Variables Revisited
  • 4.8 Calling local() on Package Variables
  • 5 Subroutines
  • 5.1 Subroutine Sigil
  • 5.2 Named Subroutines
  • 5.3 Anonymous Subroutines
  • 5.4 Data::Dumper and subroutines
  • 5.5 Passing Arguments to/from a Subroutine
  • 5.6 Accessing Arguments inside Subroutines via @_
  • 5.7 Dereferencing Code References
  • 5.8 Implied Arguments
  • 5.9 Subroutine Return Value
  • 5.10 Returning False
  • 5.11 Using the caller() Function in Subroutines
  • 5.12 The caller() function and $wantarray
  • 5.13 Context Sensitive Subroutines with wantarray()
  • 6 Compiling and Interpreting
  • 7 Code Reuse, Perl Modules
  • 8 The use Statement
  • 9 The use Statement, Formally
  • 9.1 The @INC Array
  • 9.2 The use lib Statement
  • 9.3 The PERL5LIB and PERLLIB Environment Variables
  • 9.4 The require Statement
  • 9.5 MODULENAME -> import (LISTOFARGS)
  • 9.6 The use Execution Timeline
  • 10 bless()
  • 11 Method Calls
  • 11.1 Inheritance
  • 11.2 use base
  • 11.5 Interesting Invocants
  • 12 Procedural Perl
  • 13 Object Oriented Perl
  • 13.1 Class
  • 13.2 Polymorphism
  • 13.3 SUPER
  • 13.4 Object Destruction
  • 14 Object Oriented Review
  • 14.1 Modules
  • 14.2 use Module
  • 14.3 bless / constructors
  • 14.4 Methods
  • 14.5 Inheritance
  • 14.6 Overriding Methods and SUPER
  • 15 CPAN
  • 15.1 CPAN, The Web Site
  • 15.2 CPAN, The Perl Module
  • 15.3 Plain Old Documentation (POD) and perldoc
  • 15.4 Creating Modules for CPAN with h2xs
  • 16 The Next Level
  • 17 Command Line Arguments
  • 17.1 @ARGV
  • 17.2 Getopt::Declare
  • 17.2.1 Getopt::Declare Sophisticated Example
  • 18 File Input and Output
  • 18.1 open
  • 18.2 close
  • 18.3 read
  • 18.4 write
  • 18.5 File Tests
  • 18.6 File Globbing
  • 18.7 File Tree Searching
  • 19 Operating System Commands
  • 19.1 The system() function
  • 19.2 The Backtick Operator
  • 19.3 Operating System Commands in a GUI
  • 20 Regular Expressions
  • 20.1 Variable Interpolation
  • 20.2 Wildcard Example
  • 20.3 Defining a Pattern
  • 20.4 Metacharacters
  • 20.5 Capturing and Clustering Parenthesis
  • 20.5.1 $1, $2, $3, etc Capturing parentheses
  • 20.5.2 Capturing parentheses not capturing
  • 20.6 Character Classes
  • 20.6.1 Metacharacters Within Character Classes
  • 20.7 Shortcut Character Classes
  • 20.8 Greedy (Maximal) Quantifiers
  • 20.9 Thrifty (Minimal) Quantifiers
  • 20.10 Position Assertions / Position Anchors
  • 20.10.1 The \b Anchor
  • 20.10.2 The \G Anchor
  • 20.11 Modifiers
  • 20.11.1 Global Modifiers
  • 20.11.2 The m And s Modifiers
  • 20.11.3 The x Modifier
  • 20.12 Modifiers For m{} Operator
  • 20.13 Modifiers for s{}{} Operator
  • 20.14 Modifiers for tr{}{} Operator
  • 20.15 The qr{} function
  • 20.16 Common Patterns
  • 20.17 Regexp::Common
  • 21 Parsing with Parse::RecDescent
  • 22 Perl, GUI, and Tk
  • 23 GNU Free Documentation License
  • GNU Free Documentation License

Impatient Perl

version: 9 September 2010
Copyright 2004-2010 Greg London
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.
or any !ater "ersion pub!ished by the Free #oft$are Foundation%
$ith no &n"ariant #ections, no Front'(o"er )e*ts, and no +ac,'(o"er )e*ts.
- copy of the !icense is inc!uded in the section entit!ed .GNU
Free Documentation License..
Cover rt !"ront and #a$%& on the paperba$% version o' Impatient Perl is e($l)ded 'rom
this li$ense* Cover rt is Copyright Greg London 2004+ ll ,ights ,eserved*
"or latest version o' this -or% go to:
Table of Contents
1 /he Impatient Introd)$tion to Perl**********************************************************************************************************0
1*1 /he history o' perl in 100 -ords or less******************************************************************************************0
1*2 #asi$ "ormatting 'or this 1o$)ment***********************************************************************************************0
1*2 1o 3o) 4ave Perl Installed*************************************************************************************************************5
1*4 3o)r "irst Perl S$ript+ 676,**********************************************************************************************************9
1*8 1e'a)lt S$ript 4eader**********************************************************************************************************************9
1*9 "ree ,e'eren$e :aterial****************************************************************************************************************10
1*0 Cheap ,e'eren$e :aterial*************************************************************************************************************10
1*5 $ronyms and /erms********************************************************************************************************************10
2 Storage**************************************************************************************************************************************************11
2*1 S$alars*******************************************************************************************************************************************11
2*1*1 S$alar Strings*************************************************************************************************************************12
2*1*1*1 String Literals*****************************************************************************************************************12
2*1*1*2 Single ;)otes vers)s 1o)ble ;)otes******************************************************************************12
2*1*1*2 $homp*****************************************************************************************************************************12
2*1*1*4 $on$atenation*****************************************************************************************************************12
2*1*1*8 repetition************************************************************************************************************************12
2*1*1*9 length******************************************************************************************************************************12
2*1*1*0 s)bstr******************************************************************************************************************************12
2*1*1*5 split*********************************************************************************************************************************14
2*1*1*9 <oin*********************************************************************************************************************************14
2*1*1*10 ;-*********************************************************************************************************************************18
2*1*1*11 :)lti-Line Strings+ 46,6 1o$)ments************************************************************************18
2*1*2 S$alar =)mbers**********************************************************************************************************************19
2*1*2*1 =)meri$ Literals************************************************************************************************************19
2*1*2*2 =)meri$ ")n$tions*********************************************************************************************************19
2*1*2*2 abs**********************************************************************************************************************************19
2*1*2*4 int***********************************************************************************************************************************19
2*1*2*8 trigonometry !sin+$os&****************************************************************************************************10
2*1*2*9 e(ponentiation****************************************************************************************************************10
2*1*2*0 s;rt**********************************************************************************************************************************10
2*1*2*5 nat)ral logarithms!e(p+log&********************************************************************************************15
2*1*2*9 random n)mbers !rand+ srand&***************************************************************************************15
2*1*2 Converting #et-een Strings and =)mbers***********************************************************************19
2*1*2*1 Stringi'y*************************************************************************************************************************19
2*1*2*1*1 sprint'*********************************************************************************************************************19
2*1*2*2 =)mi'y***************************************************************************************************************************20
2*1*2*2*1 o$t***************************************************************************************************************************21
2*1*2*2*2 he(**************************************************************************************************************************21
2*1*2*2*2 #ase Conversion >vervie-************************************************************************************21
2*1*4 ?nde'ined and ?ninitiali@ed S$alars*************************************************************************************22
2*1*8 #ooleans********************************************************************************************************************************22
2*1*8*1 "LS6***************************************************************************************************************************24
2*1*8*2 /,?6*****************************************************************************************************************************24
2*1*8*2 Comparators*******************************************************************************************************************28
2*1*8*4 Logi$al >perators***********************************************************************************************************29
2*1*8*4*1 1e'a)lt 7al)es********************************************************************************************************20
2*1*8*4*2 "lo- Control**********************************************************************************************************20
2*1*8*4*2 Pre$eden$e**************************************************************************************************************20
2*1*8*4*4 ssignment Pre$eden$e******************************************************************************************20
2*1*8*4*8 "lo- Control Pre$eden$e***************************************************************************************25
2*1*8*4*9 Conditional >perator**********************************************************************************************25
2*1*9 ,e'eren$es******************************************************************************************************************************29
2*1*0 "ilehandles*****************************************************************************************************************************21
2*1*5 S$alar ,evie-************************************************************************************************************************22
2*2 rrays********************************************************************************************************************************************22
2*2*1 s$alar !Aarray&**********************************************************************************************************************22
2*2*2 p)sh!Aarray+ LIS/&***************************************************************************************************************24
2*2*2 pop!Aarray&***************************************************************************************************************************24
2*2*4 shi't!Aarray&**************************************************************************************************************************28
2*2*8 )nshi't! Aarray+ LIS/&**********************************************************************************************************28
2*2*9 'orea$h !Aarray&********************************************************************************************************************29
2*2*0 sort!Aarray&***************************************************************************************************************************20
2*2*5 reverse!Aarray&*********************************************************************************************************************25
2*2*9 spli$e!Aarray&***********************************************************************************************************************29
2*2*10 ?nde'ined and ?ninitiali@ed rrays************************************************************************************29
2*2 4ashes*******************************************************************************************************************************************29
2*2*1 e(ists ! BhashCB%eyD &************************************************************************************************************41
2*2*2 delete ! BhashC%eyD &*************************************************************************************************************42
2*2*2 %eys! Ehash &*************************************************************************************************************************42
2*2*4 val)es! Ehash &**********************************************************************************************************************42
2*2*8 ea$h! Ehash &*************************************************************************************************************************42
2*4 List Conte(t***********************************************************************************************************************************40
2*8 ,e'eren$es*************************************************************************************************************************************49
2*8*1 =amed ,e'erents*******************************************************************************************************************80
2*8*2 ,e'eren$es to =amed ,e'erents*********************************************************************************************80
2*8*2 1ere'eren$ing************************************************************************************************************************80
2*8*4 nonymo)s ,e'erents***********************************************************************************************************81
2*8*8 Comple( 1ata Str)$t)res*******************************************************************************************************82
2*8*8*1 )tovivi'i$ation*************************************************************************************************************84
2*8*8*2 :)ltidimensional rrays***********************************************************************************************88
2*8*8*2 1eep Cloning+ 1eep Copy*********************************************************************************************89
2*8*8*4 1ata Persisten$e*************************************************************************************************************89
2*8*9 Stringi'i$ation o' ,e'eren$es*************************************************************************************************89
2*8*0 /he re'!& ')n$tion*******************************************************************************************************************80
2 Control "lo-*****************************************************************************************************************************************85
2*1 Labels********************************************************************************************************************************************90
2*2 last L#6LF**********************************************************************************************************************************90
2*2 ne(t L#6LF*********************************************************************************************************************************90
2*4 redo L#6LF*********************************************************************************************************************************90
4 Pa$%ages and =amespa$es and Le(i$al S$oping**********************************************************************************91
4*1 Pa$%age 1e$laration**********************************************************************************************************************91
4*2 1e$laring Pa$%age 7ariables Gith o)r*****************************************************************************************92
4*2 Pa$%age 7ariables inside a Le(i$al S$ope************************************************************************************92
4*4 Le(i$al S$ope********************************************************************************************************************************92
4*8 Le(i$al 7ariables***************************************************************************************************************************92
4*9 Garbage Colle$tion************************************************************************************************************************98
4*9*1 ,e'eren$e Co)nt Garbage Colle$tion************************************************************************************98
4*9*2 Garbage Colle$tion and S)bro)tines*************************************************************************************99
4*0 Pa$%age 7ariables ,evisited*********************************************************************************************************90
4*5 Calling lo$al!& on Pa$%age 7ariables********************************************************************************************95
8 S)bro)tines********************************************************************************************************************************************99
8*1 S)bro)tine Sigil*****************************************************************************************************************************99
8*2 =amed S)bro)tines***********************************************************************************************************************99
8*2 nonymo)s S)bro)tines***************************************************************************************************************00
8*4 1ata::1)mper and s)bro)tines******************************************************************************************************00
8*8 Passing rg)ments to.'rom a S)bro)tine**************************************************************************************00
8*9 $$essing rg)ments inside S)bro)tines via AH*************************************************************************01
8*0 1ere'eren$ing Code ,e'eren$es****************************************************************************************************01
8*5 Implied rg)ments************************************************************************************************************************02
8*9 S)bro)tine ,et)rn 7al)e***************************************************************************************************************02
8*10 ,et)rning "alse****************************************************************************************************************************02
8*11 ?sing the $aller!& ")n$tion in S)bro)tines**********************************************************************************04
8*12 /he $aller!& ')n$tion and B-antarray******************************************************************************************08
8*12 Conte(t Sensitive S)bro)tines -ith -antarray!&*************************************************************************08
9 Compiling and Interpreting*******************************************************************************************************************09
0 Code ,e)se+ Perl :od)les********************************************************************************************************************05
5 /he )se Statement*********************************************************************************************************************************05
9 /he )se Statement+ "ormally****************************************************************************************************************09
9*1 /he AI=C rray***************************************************************************************************************************09
9*2 /he )se lib Statement********************************************************************************************************************50
9*2 /he P6,L8LI# and P6,LLI# 6nvironment 7ariables***************************************************************50
9*4 /he re;)ire Statement*******************************************************************************************************************50
9*8 :>1?L6=:6 -I import !LIS/>",GS&******************************************************************************51
9*9 /he )se 6(e$)tion /imeline**********************************************************************************************************52
10 bless!&**************************************************************************************************************************************************52
11 :ethod Calls***************************************************************************************************************************************58
11*1 Inheritan$e***********************************************************************************************************************************59
11*2 )se base****************************************************************************************************************************************50
11*2 I=7>C=/-Iisa!#S6PCJG6&****************************************************************************************55
11*4 I=7>C=/-I$an!:6/4>1=:6&***************************************************************************************55
11*8 Interesting Invo$ants*******************************************************************************************************************55
12 Pro$ed)ral Perl************************************************************************************************************************************90
12 >b<e$t >riented Perl****************************************************************************************************************************90
12*1 Class********************************************************************************************************************************************94
12*2 Polymorphism*****************************************************************************************************************************94
12*2 S?P6,*****************************************************************************************************************************************98
12*4 >b<e$t 1estr)$tion***********************************************************************************************************************90
14 >b<e$t >riented ,evie-**********************************************************************************************************************95
14*1 :od)les***************************************************************************************************************************************95
14*2 )se :od)le**********************************************************************************************************************************95
14*2 bless . $onstr)$tors**********************************************************************************************************************95
14*4 :ethods***************************************************************************************************************************************99
14*8 Inheritan$e***********************************************************************************************************************************99
14*9 >verriding :ethods and S?P6,************************************************************************************************99
18 CP=************************************************************************************************************************************************100
18*1 CP=+ /he Geb Site****************************************************************************************************************100
18*2 CP=+ /he Perl :od)le***********************************************************************************************************100
18*2 Plain >ld 1o$)mentation !P>1& and perldo$***************************************************************************102
18*4 Creating :od)les 'or CP= -ith h2(s************************************************************************************102
19 /he =e(t Level**********************************************************************************************************************************104
10 Command Line rg)ments***************************************************************************************************************104
10*1 A,G7************************************************************************************************************************************108
10*2 Getopt::1e$lare*************************************************************************************************************************100
10*2*1 Getopt::1e$lare Sophisti$ated 6(ample****************************************************************************105
15 "ile Inp)t and >)tp)t************************************************************************************************************************110
15*1 open*******************************************************************************************************************************************110
15*2 $lose*******************************************************************************************************************************************110
15*2 read********************************************************************************************************************************************110
15*4 -rite*******************************************************************************************************************************************111
15*8 "ile /ests***********************************************************************************************************************************112
15*9 "ile Globbing*****************************************************************************************************************************112
15*0 "ile /ree Sear$hing*******************************************************************************************************************112
19 >perating System Commands***********************************************************************************************************114
19*1 /he system!& ')n$tion****************************************************************************************************************114
19*2 /he #a$%ti$% >perator**************************************************************************************************************114
19*2 >perating System Commands in a G?I************************************************************************************114
20 ,eg)lar 6(pressions**************************************************************************************************************************118
20*1 7ariable Interpolation****************************************************************************************************************119
20*2 Gild$ard 6(ample*********************************************************************************************************************110
20*2 1e'ining a Pattern**********************************************************************************************************************110
20*4 :eta$hara$ters***************************************************************************************************************************115
20*8 Capt)ring and Cl)stering Parenthesis***************************************************************************************120
20*8*1 B1+ B2+ B2+ et$ Capt)ring parentheses********************************************************************************120
20*8*2 Capt)ring parentheses not $apt)ring*********************************************************************************121
20*9 Chara$ter Classes**********************************************************************************************************************121
20*9*1 :eta$hara$ters Githin Chara$ter Classes*************************************************************************122
20*0 Short$)t Chara$ter Classes********************************************************************************************************122
20*5 Greedy !:a(imal& K)anti'iers**************************************************************************************************122
20*9 /hri'ty !:inimal& K)anti'iers***************************************************************************************************122
20*10 Position ssertions . Position n$hors***********************************************************************************124
20*10*1 /he Lb n$hor******************************************************************************************************************124
20*10*2 /he LG n$hor*****************************************************************************************************************128
20*11 :odi'iers*********************************************************************************************************************************120
20*11*1 Global :odi'iers**************************************************************************************************************120
20*11*2 /he m nd s :odi'iers****************************************************************************************************120
20*11*2 /he ( :odi'ier*****************************************************************************************************************129
20*12 :odi'iers "or mCD >perator***************************************************************************************************120
20*12 :odi'iers 'or sCDCD >perator**************************************************************************************************120
20*14 :odi'iers 'or trCDCD >perator*************************************************************************************************120
20*18 /he ;rCD ')n$tion********************************************************************************************************************120
20*19 Common Patterns********************************************************************************************************************120
20*10 ,ege(p::Common********************************************************************************************************************121
21 Parsing -ith Parse::,e$1es$ent********************************************************************************************************122
22 Perl+ G?I+ and /%******************************************************************************************************************************128
22 G=? "ree 1o$)mentation Li$ense***************************************************************************************************129
- /uic, e*p!anation of the re"ision history.
& !ost the origina! 0pen 0ffice fi!es for
1&mpatient Per!2. )o reco"er, & had to ta,e the
PDF, copy and paste the te*t, and then manua!!y
reformat the document to resemb!e its origina!
!ayout. &t $as painfu!!y tedious, but the re"ision
on 13 February 4556 is that reconstructed "ersion.
0ne of the prob!ems $ith that "ersion is that the
te*t had hard'returns coded into it from the
cut/paste. &t might !oo, !i,e there7s a four'!ine
paragraph on some page, but it7s rea!!y four !ines
$ith hard'coded 18n2 at the end of each !ine.
)he 9anuary 4515 "ersion attempts to remo"e a!! the
hard'coded returns in the paragraph te*t and a!!o$
the $ord processor to determine $here to $rap the
:hi!e & $as $or,ing on that re", & fi*ed a coup!e
of typos and t$ea,ed a sentence or t$o.
;n<oy= Greg London
1 The Impatient Introduction to Perl
/his do$)ment is 'or people -ho either -ant to learn perl or are already programming in perl and <)st
do not have the patien$e to s$ro)nge 'or in'ormation to learn and )se perl* /his do$)ment sho)ld also
'ind )se as a handy des% re'eren$e 'or some o' the more
$ommon perl related ;)estions*
1.1 The history of perl in 100 words or less
In the mid 1950s+ Larry Gall -as -or%ing as a sys-admin and 'o)nd that he needed to do a n)mber o'
$ommon+ yet oddball ')n$tions over and over again* nd he did not li%e any o' the s$ripting lang)ages
that -ere aro)nd at the time+ so he invented Perl* 7ersion 1 -as released $ir$a 1950* 'e- $hanges
have o$$)rred bet-een then and no-* /he $)rrent version o' Perl has e($eeded 8*5*2 and is a highly
re$ommended )pgrade*
Perl 9 is on the dra-ing board as a ')ndamental re-rite o' the lang)age* It is not available yet+ and
probably -ill not be available 'or some time*
1.2 Basic Formatting for this Document
/his do$)ment is 'ormatted into te(t se$tions+ $ode se$tions+ and shell se$tions* /his senten$e is part o'
a te(t se$tion* /e(t se$tions -ill e(tend to the 'ar le't margin and -ill )se a non-monospa$ed 'ont* /e(t
se$tions $ontain des$riptive te(t*
(ode sections are indented.
)hey a!so use a monospaced font.
)his is a code section, $hich represents
code to type into a script.
>ou $i!! need to use a );?) ;D&)0@,
not a :0@D P@0(;##0@ to create these fi!es.
Genera!!y, the code is contained in one fi!e,
and is e*ecuted "ia a she!! command.
&f the code section co"ers mu!tip!e fi!es,
each fi!e $i!! be !abe!ed.
)his code $i!! be p!aced in a
fi!e ca!!ed CyFi!e.pm
A=/usr/!oca!/en" per!
)his code $i!! be p!aced in a fi!e
ca!!ed myscript.p!
)he first !ine of myscript.p! $i!! be the
!ine $ith A=/usr/!oca!/en" per!
D she!! sections are indented !i,e code sections
D she!! sections a!so use monospaced fonts.
D she!! sections differ from code sections in
D that she!! sections start $ith a 7D7 character
D $hich represents a she!! prompt.
D she!! sections sho$ commands to type on
D the command !ine.
D she!! sections a!so sho$ the output of a script,
D if any e*ists.
D &n simp!e e*amp!es, the code is sho$n in a
D code section, immediate!y fo!!o$ed by the output
D from running the script. )he command to run
D the script is dropped to sa"e space.
s an e(ample+ the $ode 'or a simple M4ello GorldM s$ript is sho-n here* It $an be typed into a 'ile o'
any name* /he name o' the 'ile is not important* /he $ommand to e(e$)te the s$ript is not important
either* In this e(ample+ the $ode is important+ and the o)tp)t is important+ so they are they only things
print .Ee!!o :or!d8n.%
D Ee!!o :or!d
/4IS 1>C?:6=/ ,6"6,S /> !LI.?&=IN P6,L >=L3* :)$h o' this -ill translate to :a$ Perl
and Gindo-s Perl+ b)t the e(a$t translation -ill be le't as an e(er$ise to the reader*
1.3 Do You Hae !erl "nstalled
/o 'ind o)t i' yo) have perl installed and its version:
D per! '"
3o) sho)ld have at least version 8*5*2* I' yo) have an older version or i' yo) have no perl installed at
all+ yo) $an do-nload it 'or 'ree 'rom
CP= is an a$ronym 'or Comprehensive Perl r$hive =et-or%* /he CP= site $ontains the latest perl
'or do-nload and installation+ as -ell as a />= o' perl mod)les 'or yo)r )se*
I' yo) are a beginner+ get yo)r sys-admin to install perl 'or yo)* 6ven i' yo) are not a beginner+ get
yo)r sys-admin to install perl 'or yo)*
1.# Your First !erl $cript% &'&(
Create a 'ile $alled hello*pl )sing yo)r 'avorite te(t editor* /ype in the 'ollo-ing:
A=/usr/bin/en" per!
use $arnings%
use strict% A comment
print .Ee!!o :or!d 8n.%
!/he OP on the 'irst line is sometimes prono)n$ed MshebangM&
!/he *pl e(tension is simply a standard a$$epted e(tension 'or perl s$ripts*&
,)n the s$ript:
D per! he!!o.p!
Ee!!o :or!d
/his $alls perl and passes it the name o' the s$ript to e(e$)te* 3o) $an save yo)rsel' a little typing i'
yo) ma%e the 'ile e(e$)table:
D chmod F* he!!o.p!
nd then r)n the s$ript dire$tly*
D he!!o.p!
Ee!!o :or!d
I' "." is not in yo)r PATH variable+ yo) -ill have to r)n the s$ript by typing:
D ./he!!o.p!
4>>,3P =o- go )pdate yo)r res)me*
nything 'rom a O $hara$ter to the end o' the line is a $omment*
1.) Default $cript Header
ll the $ode e(amples in this do$)ment are ass)med to have the 'ollo-ing s$ript header+ )nless
other-ise stated* It )ses yo)r P/4 environment variable to determine -hi$h perl e(e$)table to r)n* I'
yo) need to have di''erent versions o' perl installed on yo)r system+ yo) $an $ontrol -hi$h version o'
perl they -ill r)n by $hanging yo)r P/4 variable -itho)t having to $hange yo)r s$ript*
A=/usr/bin/en" per!
use $arnings%
use strict%
use Data::Dumper;
Note that Data::Dumper takes some time to load and you wouldn't want
to use Data::Dumper on some timing-critical project. But for learning
perl with simple scripts, the execution speed isn't that high of a
priority. If you're writing a “real” script (i.e. one where time-to-
run and memory-usage are issues to be considered), then don't use
Data::Dumper by default, only use it if you really need it.
1.* Free (eference +aterial
3o) $an get ;)i$% help 'rom the standard perl installation*
D per! 'h
D per!doc
D per!doc 'h
D per!doc per!doc
"Ks on CP=: http:..---*$pan*org.$pan-'a;*html
:ailing Lists on CP=: http:..list*$pan*org
:ore 'ree do$)mentation on the -eb: http:..---*perldo$*$om
Still more 'ree do$)mentation on the -eb: http:..learn*perl*org
1., -heap (eference +aterial
MProgramming PerlM by Larry Gall+ /om Christiansen+ and Qon >r-ant* 4ighly re$ommended boo% to
have handy at all times* It is sometimes re'erred to as the MCamel #oo%M by -ay o' the $amel dra-ing
on its $over* /he p)blisher+ >R,eilly+ has printed eno)gh $omp)ter boo%s to $ho%e a+ -ell+ $amel+ and
ea$h one has a di''erent animal on its $over* /here'ore i' yo) hear re'eren$e to some animal boo%+ it is
probably an >R,eilly boo%* Gell+ )nless its the M1ragon #oo%M+ be$a)se that re'ers to a boo% $alled
MCompilersM by ho+ Sethi+ and ?llman*
1.. /cronyms and Terms
Perl: >riginally+ MPearlM shortened to MPerlM to gain stat)s as a 4-letter -ord* =o- $onsidered an
a$ronym 'or Pra$ti$al 6(tra$tion and ,eport Lang)age+ as -ell as Petty 6$le$ti$ ,)bbish Lister* /he
name -as invented 'irst* /he a$ronyms 'ollo-ed* =ote that this is MPerlM -ith a $apital MPM* /he MperlM
-ith a lo-er $ase MpM re'ers to the e(e$)table 'o)nd some-here near .)sr.lo$al.bin.perl
CP=: Comprehensive Perl r$hive =et-or%* See http:..---*$pan*org 'or more*
1GI:: 1o Ghat I :ean* >n$e )pon a time+ the standard mantra 'or $omp)ter in'le(ibility -as this: MI
really hate this darn ma$hine+ I -ish that they -o)ld sell it* It never does -hat I -ant+ b)t only -hat I
tell it*M 1GI:-iness is an attempt to embed perl -ith telepathi$ po-ers s)$h that it $an )nderstand
-hat yo) -anted to -rite in yo)r $ode even tho)gh yo) 'orgot to a$t)ally type it* Gell+ alright+ 1GI:
is <)st a -ay o' saying the lang)age -as designed by some really la@y programmers so that yo) $o)ld
be even la@ier than they -ere* !/hey had to -rite perl in C+ so they $o)ld not be />> la@y*&
?/>7I7I"3: Ma)toM meaning Msel'M* Mvivi'yM meaning MaliveM* /o bring onesel' to li'e* Generally
applies to perl variables that $an grant themselves into being -itho)t an e(pli$it de$laration 'rom the
programmer* Part o' perlRs 1GI:-ness* M)tovivi'yM is a verb* /he no)n 'orm is Ma)tovivi'i$ationM*
Sometimes+ a)tovivi'i$ation is not -hat yo) meant yo)r $ode to do+ and 'or some reason+ -hen Mdo
-hat I meanM meets a)tovivi'i$ation in perl+ a)tovivi'i$ation -ins*
nd no-+ a 4ai%):
Do :hat & Cean and
sometimes un$anted
/:/>G/1I: /here is :ore /han >ne Gay /o 1o It* n a$%no-ledgment that any programming
problem has more than one sol)tion* ,ather than have perl de$ide -hi$h sol)tion is best+ it gives yo)
all the tools and lets yo) $hoose* /his allo-s a programmer to sele$t the tool that -ill let him get his
<ob done* Sometimes+ it gives a perl ne-bie <)st eno)gh rope to hang himsel'*
"oo "ighters: phrase )sed aro)nd the time o' GGII by radar operators to des$ribe a signal that $o)ld
not be e(plained* Later be$ame %no-n as a ?">* /his has nothing to do -ith perl+ e($ept that M'ooM is
a $ommon variable name )sed in perl*
")bar: nother GGII phrase )sed to indi$ate that a mission had gone serio)sly a-ry or that a pie$e o'
e;)ipment -as inoperative* n a$ronym 'or "o)led ?p #eyond ll ,e$ognition and similar
interpretations* /his has nothing to do -ith perl either+ e($ept that ')bar someho- got mangled into
'oobar+ and perl is o'ten a-ash in variables named M'ooM and MbarM+ espe$ially i' the programmer
-ishes to hide the 'a$t that he did not )nderstand his $ode -ell eno)gh to $ome )p -ith better names* I'
yo) )se a B'oo variable in yo)r $ode+ yo) deserve to maintain it*
2 Storage
Perl has three basi$ storage types: S$alars+ rrays+ and 4ashes*
/he most basi$ storage type is a S$alar*
rrays and 4ashes )se S$alars to b)ild more $omple( data types*
2.1 $calars
S$alars are pre$eded -ith a dollar sign sigil* MBM is a styli@ed MSM*
sigil : symbol* In Perl a sigil re'ers to the symbol in 'ront o' a variable*
S$alars $an store Strings+ =)mbers !integers and 'loats&+ ,e'eren$es+ and "ilehandles* Perl is smart
eno)gh to %no- -hi$h type yo) are p)tting into a s$alar and handle it*
my Gdiameter H I4% A )he 1my2 ,ey$ord dec!ares a !e*ica!
my Gpi H .1I1J% A "ariab!e. &f you don7t ,no$ $hat
my Ginitia! H 7g7% A that means, don7t $orry about it,
my Gname H 79ohn Doe7% A it $i!! be e*p!ained !ater.
my GrefKtoKname H 8Gname A #pecifica!!y, in section I
Githo)t M)se stri$tFM and -itho)t de$laring a variable -ith a MmyM+ )sing a variable $a)ses perl to
$reate one and initiali@e it to )nde'* /his )nde' val)e -ill stringi'y to MM or n)mi'y to 0+ depending ho-
the )nde'ined variable is )sed* /his is $alled a)tovivi$ation* !Stringi'i$ation and =)mi'i$ation are
$overed later*&
Autovivify : to bring oneself to life.
In some sit)ations+ a)tovivi$ation is handy* 4o-ever+ in $ertain sit)ations+ a)tovivi'i$ation $an be an
)nholy monster*
my Gcircumference H Gpie L Gdiameter%
A oops, Gpie doesn7t e*ist. -uto"i"ified to undef,
A numified to 5, therefore Gcircumference is Mero.
Githo)t use warnings; use strict; perl -ill a)tovivi'y a ne- variable $alled MpieM+
initiali@e it to @ero+ and ass)me that is -hat yo) meant to do* /here is no reason that -arnings and
stri$tness sho)ld not be t)rned on in yo)r s$ripts*
2.1.1 Scalar Strings
S$alars $an store strings* 3o) do not have to de$lare the length o' the string+ perl <)st handles it 'or yo)
a)tomati$ally* $tring 0iterals
String literals m)st be in single or do)ble ;)otes or yo) -ill get an error*
print he!!o%
;rrorB Un/uoted string .he!!o. may c!ash $ith
reser"ed $ord
3o) $an )se single ;)otes or do)ble ;)otes to set o'' a string literal:
my Gname H 7mud7%
my Ggreeting H .he!!o, Gname8n.%
print Ggreeting%
D he!!o, mud
3o) $an also $reate a list o' string literals )sing the ;-!& ')n$tion*
my NGfirst,G!astOH/$N 9ohn Doe O%
print .first is 7Gfirst78n.%
print .!ast is 7G!ast78n.%
D first is 79ohn7
D !ast is 7Doe7
12 $ingle 1uotes ersus Dou2le 1uotes
Single ;)oted strings are a M-hat yo) see is -hat yo) getM %ind o' thing*
my Gname H 7mud7%
print 7he!!o Gname7%
D he!!o Gname
1o)ble ;)otes means that yo) get S>:6 variable interpolation d)ring string eval)ation* Comple(
variables+ s)$h as a hash loo%)p+ -ill not be interpolated properly in do)ble ;)otes*
my Gname H 7mud7%
print .he!!o Gname 8n.%
D he!!o mud
=ote: a do)ble-;)oted MLnM is a ne--line $hara$ter* chomp
3o) may get rid o' a ne-line $hara$ter at the end o' a string by $homp-ing the string* /he $homp
')n$tion removes one ne- line 'rom the end o' the string even i' there are m)ltiple ne-lines at the end*
I' there are no ne-lines+ $homp leaves the string alone* /he ret)rn val)e o' $homp is -hat -as
$homped !seldom )sed&*
Cy Gstring H .he!!o $or!d8n.%
$arn .string is 7Gstring7 8n.
D string is 7he!!o $or!d7 ...
2.1.1.# concatenation
String $on$atenation )ses the period $hara$ter M*M
my Gfu!!name H 7mud7 . .bath.%
2.1.1.) repetition
,epeat a string -ith the M(M operator*
my G!ine H 7'7 * P5% A G!ine is eighty hypens
2.1.1.* length
"ind o)t ho- many $hara$ters are in a string -ith length!&*
my G!en H !engthNG!ineO% A G!en is P5
2.1.1., su2str
substr N #)@&NGK;?P@;##&0N, 0FF#;), L;NG)EO%
Spin+ 'old+ and m)tilate strings )sing s)bstr!&* /he s)bstr ')n$tion gives yo) 'ast a$$ess to get and
modi'y $h)n%s o' a string* 3o) $an ;)i$%ly get a $h)n% o' L6=G/4 $hara$ters starting at >""S6/
'rom the beginning or end o' the string !negative o''sets go 'rom the end&* /he s)bstr ')n$tion then
ret)rns the $h)n%*
my Gchun, H substrN7the rain in spain7, 6, 4O%
$arn .chun, is 7Gchun,7.%
D chun, is 7in7 ...
/he s)bstr ')n$tion $an also be assigned to+ repla$ing the $h)n% as -ell* 3o) need a string $ontained in
a variable that $an be modi'ied+ rather than )sing a $onstant literal in the e(ample above*
my Gstring H 7the rain in spain7%
substrNGstring, 6, 4O H 7beyond7%
$arn .string is 7Gstring7.%
D string is 7the rain beyond spain7 ...
2.1.1.. split
sp!itN/P-));@N/, #)@&NGK;?P@;##&0N,L&C&)O%
?se the split ')n$tion to brea% a string e(pression into $omponents -hen the $omponents are separated
by a $ommon s)bstring pattern* "or e(ample+ tab separated data in a single string $an be split into
separate strings*
my GtabKsepKdata H .9ohn8tDoe8tma!e8tI4.%
my NGfirst,G!ast,Ggender,GageO
H sp!itN/8t/, GtabKsepKdataO%
3o) $an brea% a string into individ)al $hara$ters by $alling split -ith an empty string pattern MM* /he
.P//6,=. in split!& is a ,eg)lar 6(pression+ -hi$h is $ompli$ated eno)gh to get its o-n $hapter*
4o-ever+ some $ommon reg)lar e(pression P//6,=S 'or split are:
8t tab'separated data
8sF $hitespace'separated data
8sL,8sL comma'separated data 4oin
<oinN7#;P-@-)0@ #)@&NG7, #)@&NG1, #)@&NG4, ...O%
?se <oin to stit$h a list o' strings into a single string*
my Gstring H <oinN. and .,
7app!es7, 7bananas7, 7peaches7O%
$arn .string is 7Gstring7.%
D string is 7app!es and bananas and peaches7...
14 1w
/he ;-!& ')n$tion ta%es a list o' bare-ords and ;)otes them 'or yo)*
my Gstring H
<oinN. and ., /$Napp!es bananas peachesOO%
$arn .string is 7Gstring7.%
D string is 7app!es and bananas and peaches7... +ulti50ine $trings% H&(& Documents
Perl allo-s yo) to pla$e a m)lti-line string in yo)r $ode by )sing -hat it $alls a Mhere do$)mentS*
Cy Gstring H QQ2;ND0FD0(UC;N)2%
Do What I Mean and
sometimes unwanted
$arn .string is 7Gstring72%
D string is 7Do :hat & Cean and
D -uto"i"ification
D sometimes un$anted7 at ...
/he RTTR indi$ates a 46,6 do$)ment+ 'ollo-ed by the name o' the label indi$ating the end o' the here
do$)ment* 6n$losing the label in do)ble ;)otes means that perl variables in the do$)ment -ill get
interpolated as strings* 6n$losing the label in single ;)otes means that no string interpolation o$$)rs*
Perl then reads the lines a'ter the RTTR as string literal $ontent )ntil it sees the end o' string label
positioned at the beginning o' a line*
2.1.2 Scalar Numbers
Perl generally )ses 'loats internally to store n)mbers* I' yo) spe$i'y something that is obvio)sly an
integer+ it -ill )se an integer* 6ither -ay+ yo) simply )se it as a s$alar*
my GdaysKinK$ee, H 3% A sca!ar HD integer
my Gtemperature H 6P.R% A sca!ar HD f!oat 6umeric 0iterals
Perl allo-s several di''erent 'ormats 'or n)meri$ literals+ in$l)ding integer+ 'loating point+ and s$ienti'i$
notation+ as -ell as de$imal+ o$tal+ and he(ade$imal*
#inary n)mbers begin -ith M0bM
he(ade$imal n)mbers begin -ith M0(M
>$tal n)mber begin -ith a M0M
ll other n)meri$ literals are ass)med to be de$imal*
my Gso!arKtempKc H 1.Je3% A centigrade
my Gso!arKtempKf H 43K555K555.5% A Fahrenheit
my GbaseKaddress H 514IJR3% A octa!
my GhighKaddress H 5*fa6I% A he*adecima!
my G!o$Kaddress H 5b155151% A binary 6umeric Functions a2s
?se abs to get the absol)te val)e o' a n)mber*
my G"ar1 H absN'.IO% A "ar1 is .I
my G"ar4 H absNJ.6O% A "ar4 is J.6
2.1.2.# int
?se MintM to $onvert a 'loating point n)mber to an integer* =ote that this tr)n$ates everything a'ter the
de$imal point+ -hi$h means yo) do =>/ get ro)nding* /r)n$ating means that positive n)mbers al-ays
get smaller and negative n)mbers al-ays get bigger*
my Gprice H 6.6J%
my Gdo!!ars H int NGpriceO%
A do!!ars is 6, not 15= fa!se ad"ertising=
my GyKpos H 'J.6%
my GyKint H intNGyKposO%
A yKint is 'J N'J is .bigger. than 'J.6O
I' yo) -ant to ro)nd a 'loat to the nearest integer+ yo) -ill need to -rite a bit o' $ode* >ne -ay to
a$$omplish it is to )se sprint':
my Gprice H 6.6J%
my Gdo!!ars H sprintfN.S.5f., GpriceO%
A do!!ars is 15
2.1.2.) trigonometry 7sin%cos8
/he sin!& and $os!& ')n$tions ret)rn the sine and $osine o' a val)e given in ,1I=S* I' yo) have a
val)e in 16G,66S+ m)ltiply it by !pi.150& 'irst*
my Gang!e H IJ% A IJ deg
my Gradians H Gang!e L N .1I / 1P5 O% A .3PJ rad
my GsineKrad H sinNGradiansO% A 5.353 (orrect=
my GsineKdeg H sinNGang!eO% A 5.PJ1 00P#=
I' yo) need inverse sine+ inverse $osine+ or tangent then )se the :ath::/rig mod)le on CP=*
2.1.2.* e9ponentiation
?se the "**" operator to raise a n)mber to some po-er*
my Gse"enKs/uared H 3 LL 4% A I6
my Gfi"eKcubed H J LL % A14J
my GthreeKtoKtheKfourth H LL I% A P1
Use fractiona! po$ers to ta,e a root of a numberB
my Gs/uareKrootKofKI6 H I6 LL N1/4O% A 3
my GcubeKrootKofK14J H 14J LL N1/O% A J
my GfourthKrootKofKP1 H P1 LL N1/IO% A
Standard perl $annot handle imaginary n)mbers* ?se the :ath::Comple( mod)le on CP=*
2.1.2., s1rt
?se s;rt to ta%e the s;)are root o' a positive n)mber*
my Gs/uareKrootKofK14 H s/rtN14O% A 11.565J
2.1.2.. natural logarithms7e9p%log8
/he exp ')n$tion ret)rns e to the po-er o' the val)e given* /o get e+ $all exp(1);
my G"a!ueKofKe H e*pN1O% A 4.31P
my GbigKnumH e*pNI4O% A 4.31P LL I4 H 1.3e1P
/he log ')n$tion ret)rns the inverse e(p!& ')n$tion+ -hi$h is to say+ log ret)rns the n)mber to -hi$h
yo) -o)ld have to raise e to get the val)e passed in*
my Gin"Ke*p H !ogNGbigKnumO% A in"Ke*p H I4
I' yo) -ant another base+ then )se this s)bro)tine:
sub !ogK*KbaseKb Treturn !ogNGKU5VO/!ogNGKU1VO%W
A $ant the !og base 15 of 14IJ
A i.e. to $hat po$er do $e need to raise the
A number 15 to get the "a!ue of 14IJX
my Gans$er H !ogK*KbaseKbN14IJ,15O% A ans$er H I.1
=ote that inverse nat)ral logs $an be done -ith e(ponentiation+ yo) <)st need to %no- the val)e o' the
magi$ n)mber e !U 2*015251525&* /he e(p ')n$tion is straight'or-ard e(ponentiation:
A bigKnum H 4.31P LL I4 H 1.3e1P
my GbigKnum H G"a!ueKofKe LL I4%
=at)ral logarithms simply )se the inverse o' the val)e !i*e* 1.val)e& -ith e(ponentiation*
A in"Ke*p H 4.31P LL N1/1.3e1PO H I4
my Gin"Ke*p H G"a!ueKofKe LL N1/GbigKnumO% random num2ers 7rand% srand8
/he rand ')n$tion is a pse)dorandom n)mber generator !P,=G&*
I' a val)e is passed in+ rand ret)rns a n)mber that satis'ies ! 0 TV ret)rn TV inp)t &
I' no val)e is passed in+ rand ret)rns a n)mber in the range ! 0 TV ret)rn T 1 &
/he srand ')n$tion -ill seed the P,=G -ith the val)e passed in* I' no val)e is passed in+ srand -ill
seed the P,=G -ith something 'rom the system that -ill give it de$ent randomness* 3o) $an pass in a
'i(ed val)e to g)arantee the val)es ret)rned by rand -ill al-ays 'ollo- the same se;)en$e !and
there'ore are predi$table&* 3o) sho)ld only need to seed the P,=G on$e* I' yo) have a version o' perl
greater than or e;)al to 8*004+ yo) sho)ld not need to $all it at all+ be$a)se perl -ill $all srand at
2.1.3 -onerting Between $trings and 6um2ers
:any lang)ages re;)ire the programmer to e(pli$itly $onvert n)mbers to strings be'ore printing them
o)t and to $onvert strings to n)mbers be'ore per'orming arithmeti$ on them* Perl is not one o' these
Perl -ill attempt to apply 1o Ghat I :ean to yo)r $ode and <)st 1o /he ,ight /hing* /here are t-o
basi$ $onversions that $an o$$)r: stringi'i$ation and n)mi'i$ation* $tringify
Stringi'y: Converting something other than a string to a string 'orm*
Perl -ill a)tomati$ally $onvert a n)mber !integer or 'loating point& to a string 'ormat be'ore printing it
my Gmass H 3.%
my G"o!ume H I%
$arn .mass is 7Gmass78n.%
$arn ."o!ume is 7G"o!ume78n.%
D mass is 73.7 ...
D "o!ume is 7I7 ...
6ven tho)gh Bmass is stored internally as a 'loating point n)mber and Bvol)me is stored internally as
an integer+ the $ode did not have to e(pli$itly $onvert these n)mbers to string 'ormat be'ore printing
them o)t* Perl -ill attempt to $onvert the n)mbers into the appropriate string representation* I' yo) do
not -ant the de'a)lt 'ormat+ )se sprint'* I' yo) -ant to 'or$e stringi'i$ation+ simply $on$atenate a n)ll
string onto the end o' the val)e*
my Gmass H 3.% A 3.
my GstringKmass H Gmass .H 77% A 73.7 sprintf
?se sprint' to $ontrol e(a$tly ho- perl -ill $onvert a n)mber into string 'ormat*
sprintf N F0@C-)K#)@&NG, L&#)K0FKV-LU;# O%
"or e(ample:
my Gpi H .1I1J%
my Gstr H sprintfN.S5R.4f.,GpiO%
$arn .str is 7Gstr7.%
D str is 755.1I7 ...
1e$oding the above 'ormat string:
S HD format
5 HD fi!! !eading spaces $ith Mero
R HD tota! !ength, inc!uding decima! point
.4 HD put t$o p!aces after the decima! point
f HD f!oating point notation
/o $onvert a n)mber to a he(ade$imal+ o$tal+ binary+ or de$imal 'ormated string+ )se the 'ollo-ing
he*adecima! .S!*. )he !etter 7!7 NLO
octa! .S!o. indicates the input is
binary .S!b. an integer, possib!y
decima! integer .S!d. a Long integer.
decima! f!oat .Sf.
scientific .Se. 6umify
=)mi'y: Converting something other than a n)mber to a n)meri$ 'orm*
Sometimes yo) have string in'ormation that a$t)ally represents a n)mber* "or e(ample+ a )ser might
enter the string M19*98M -hi$h m)st be $onverted to a 'loat be'ore perl $an per'orm any arithmeti$ on it*
3o) $an 'or$e n)mi'i$ation o' a val)e by adding integer @ero to it*
my GuserKinput H 716.6J7% A 716.6J7
my Gprice H GuserKinputF5% A 16.6J
I' the string is =>/ in base ten 'ormat+ then )se o$t!& or he(!&
20 oct
/he oct ')n$tion $an ta%e a string that 'its the o$tal+ he(ade$imal+ or binary 'ormat and
$onvert it to an integer*
binary 'ormatted strings m)st start -ith M0bM
he(ade$imal 'ormatted strings m)st start -ith M0(M
ll other n)mbers are ass)med to be o$tal strings*
=ote: even tho)gh the string might not start -ith a @ero !as re;)ired by o$tal literals&+ o$t -ill ass)me
the string is o$tal* /his means $alling o$t!& on a de$imal n)mber $o)ld be a bad thing*
/o handle a string that $o)ld $ontain o$tal+ he(ade$imal+ binary+ >, de$imal strings+ yo) $o)ld ass)me
that o$tal strings m)st start -ith M0M* /hen+ i' the string starts -ith @ero+ $all o$t on it+ else ass)me itRs
de$imal* /his e(ample )ses reg)lar e(pressions and the $onditional operator*
my Gnum H NGstrHYmTZ5WO X octNGstrO B Gstr F 5% hex
/he he(!& ')n$tion ta%es a string in he( 'ormat and $onverts it to integer* /he he(!& ')n$tion is li%e
o$t!& e($ept that he(!& only handles he( base strings+ and it does not re;)ire a M0(M pre'i(* Base Conersion !erie"
Given a de$imal n)mber:
my Gdecima!H14%
Convert 'rom de$imal to another base )sing sprint':
my Ghe* H sprintfN.S!*., Gdecima!O%
my Goct H sprintfN.S!o., Gdecima!O%
my Gbin H sprintfN.S!b., Gdecima!O%
I' yo) -ant to pad the most signi'i$ant bits -ith @eroes and yo) %no- the -idth+ )se this:
A 5P assumes $idth is P characters
my GpKhe* H sprintfN.S5P!*., Gdecima!O%
my GpKoct H sprintfN.S5P!o., Gdecima!O%
my GpKbin H sprintfN.S5P!b., Gdecima!O%
I' yo) have a string and yo) -ant to $onvert it to de$imal+ )se the $onditional operator and o$t!&*
sub con"ertKtoKdecima! T
$arn con"ertKtoKdecima!N7I47O% A dec
$arn con"ertKtoKdecima!N7547O% A oct
$arn con"ertKtoKdecima!N75*ff7O% A he*
$arn con"ertKtoKdecima!N75b15515117O% A bin
I' yo) -ant to %no- ho- many bits it -o)ld ta%e to store a n)mber+ $onvert it to binary )sing sprint'
!donRt pad -ith @eros& and then $all length!& on it*
$arn !engthNsprintfN.S!b., 4JJOO% A P
2.1.# $ndefined and $ninitiali%ed Scalars
ll the e(amples above initiali@ed the s$alars to some %no-n val)e be'ore )sing them* 3o) $an de$lare
a variable b)t not initiali@e it+ in -hi$h $ase+ the variable is )nde'ined* I' yo) )se a s$alar that is
)nde'ined+ perl -ill stringi'y or n)mi'y it based on ho- yo) are )sing the variable*
n )nde'ined s$alar stringi'ies to an empty string: MM
n )nde'ined s$alar n)mi'ies to @ero: 0
Githo)t -arnings or stri$t t)rned on+ this $onversion is silent* Gith -arnings.stri$t on+ the $onversion
still ta%es pla$e+ b)t a -arning is emitted*
Sin$e perl a)tomati$ally per'orms this $onversion no matter -hat+ there is no string or n)meri$
operation that -ill tell yo) i' the s$alar is )nde'ined or not*
?se the de'ined!& ')n$tion to test -hether a s$alar is de'ined or not*
I' the s$alar is de'ined+ the ')n$tion ret)rns a boolean Mtr)eM !1&
I' the s$alar is =>/ de'ined+ the ')n$tion ret)rns a boolean M'alseM !MM&*
I' yo) have a s$alar -ith a de'ined val)e in it+ and yo) -ant to ret)rn it to its )ninitiali@ed state+ assign
)nde' to it* /his -ill be e(a$tly as i' yo) de$lared the variable -ith no initial val)e*
my G"ar% A undef
print .test 1 B.%
ifNdefinedNG"arOO Tprint .defined8n.%W
e!se Tprint .undefined8n.%W
G"ar H I4% A defined
print .test 4 B.%
ifNdefinedNG"arOO Tprint .defined8n.%W
e!se Tprint .undefined8n.%W
G"ar H undef% A undef as if ne"er initia!iMed
print .test B.%
ifNdefinedNG"arOO Tprint .defined8n.%W
e!se Tprint .undefined8n.%W
D test 1 Bundefined
D test 4 Bdefined
D test Bundefined
2.1.& Booleans
Perl does not have a boolean MtypeM per se* Instead+ perl interprets s$alar strings and n)mbers as Mtr)eM
or M'alseM based on some r)les:
1O#trings .. and .5. are F-L#;,
any other string or stringification is )@U;
4O Number 5 is F-L#;, any other number is )@U;
O a!! references are )@U;
IO undef is F-L#;
=ote that these are SCL,S* ny variable that is not a SCL, is 'irst eval)ated in s$alar $onte(t+
and then treated as a string or n)mber by the above r)les* /he s$alar $onte(t o' an ,,3 is its si@e*
n array -ith one )nde' val)e has a s$alar!& val)e o' 1 and is there'ore eval)ated as /,?6*
s)bro)tine ret)rns a s$alar or a list depending on the $onte(t in -hi$h it is $alled* /o e(pli$itly ret)rn
"LS6 in a s)bro)tine+ )se this:
return $antarrayNO X NO B 5% A F-L#;
/his is s)''i$iently tro)blesome to type 'or s)$h a $ommon thing that an empty ret)rn statement -ithin
a s)bro)tine -ill do the same thing:
return% AF-L#;
2.1.).1 F/0$&
/he 'ollo-ing s$alars are interpreted as "LS6:
integer 5 A fa!se
f!oat 5.5 A fa!se
string 757 A fa!se
string 77 A fa!se
undef A fa!se
2.1.).2 T(:&
LL other val)es are interpreted as /,?6+ -hi$h means the 'ollo-ing s$alars are $onsidered /,?6+
even tho)gh yo) might not have e(pe$ted them to be 'alse*
string 75.57 A true
string 7557 A true
string 7fa!se7 A true
f!oat .1I1J A true
integer 11 A true
string 7yo$ser7 A true
I' yo) are doing a lot o' -or% -ith n)mbers on a variable+ yo) may -ish to 'or$e n)mi'i$ation on that
variable ($var+0) be'ore it gets boolean tested+ <)st in $ase yo) end )p -ith a string M0*0M instead o'
a 'loat 0*0 and get some serio)sly hard to 'ind b)gs*
=ote that the string R0*0R is /,?6+ b)t !R0*0RW0& -ill get n)mi'ied to 0+ -hi$h is "LS6* I' yo) are
pro$essing a n)mber as a string and -ant to eval)ate it as a #>>L6=+ ma%e s)re yo) e(pli$itly
=?:I"3 it be'ore testing its #>>L6==6SS*
#)ilt in Perl ')n$tions that ret)rn a boolean -ill ret)rn an integer one !1& 'or /,?6 and an empty
string !MM& 'or "LS6*
2.1.).3 -omparators
Comparison operators ret)rn booleans+ spe$i'i$ally an integer 1 'or tr)e and a n)ll string "" 'or
'alse* /he "Comparison" operator !M<=>M and McmpM& ret)rn a -1+ 0+ or W1+ indi$ating the
$ompared val)es are less than+ e;)al to+ or greater than* 1istin$t $omparison operators e(ist 'or
$omparing strings and 'or $omparing n)mbers*
Function String Numeric
")n$tion String =)meri$
e/ua! to e/ HH
not e/ua! to ne =H
!ess than !t Q
greater than gt D
!ess than or e/ua! to !e QH
greater than or e/ua! to ge DH
N!tH'1, e/H5, gtHF1O
cmp QHD
equal to
=ote that i' yo) )se a string operator to $ompare t-o n)mbers+ yo) -ill get their alphabeti$al string
$omparison* Perl -ill stringi'y the n)mbers and then per'orm the $ompare* /his -ill o$$)r silentlyF perl
-ill emit no -arning* nd i' yo) -anted the n)mbers $ompared n)meri$ally b)t )sed string
$omparison+ then yo) -ill get the -rong res)lt -hen yo) $ompare the strings !"9" lt "100").
String M9M is greater than !gt& string M100M*
=)mber 9 is less than !TV& n)mber 100*
I' yo) )se a n)meri$ operator to $ompare t-o strings+ perl -ill attempt to n)mi'y the strings and then
$ompare them n)meri$ally* Comparing MQohnM TV MQa$obM -ill $a)se perl to $onvert MQohnM into a
n)mber and 'ail miserably* 4o-ever+ i' -arnings.stri$t is not on+ it -ill 'ail miserably and SIL6=/L3+
assigning the n)mi'i$ation o' MQohnM to integer @ero*
/he n)meri$ $omparison operator RTVIR is sometimes $alled the Mspa$eship operatorM*
2.1.).# 0ogical ;perators
Perl has t-o sets o' operators to per'orm logi$al =1+ >,+ =>/ ')n$tions* /he di''eren$e bet-een the
t-o is that one set has a higher pre$eden$e than the other set*
/he higher pre$eden$e logi$al operators are the RXXR+ RYYR+ and RPR operators*
function operator usage return "a!ue
-ND [[ Gone [[ Gt$o if NGone is fa!seO Gone e!se Gt$o
0@ \\ Gone \\ Gt$o if NGone is trueO Gone e!se Gt$o
N0) = = Gone if NGone is fa!seO true e!se fa!se
/he lo-er pre$eden$e logi$al operators are the RandR+ RorR+ RnotR+ and R(orR operators*
function operator usage return "a!ue
-ND and Gone and Gt$o if NGone is fa!seO Gone e!se Gt$o
0@ or Gone or Gt$o if NGone is trueO Gone e!se Gt$o
N0) not not Gone if NGone is fa!seO true e!se fa!se
?0@ *or Gone *or Gt$o if N NGone true and Gt$o fa!seO or
NGone fa!se and Gt$o trueO O then
return true e!se fa!se
#oth sets o' operators are very $ommon in perl $ode+ so it is )se')l to learn ho- pre$eden$e a''e$ts
their behavior* #)t 'irst+ some e(amples o' ho- to )se them*
2.1.&.#.1 'efault (alues
/his s)bro)tine has t-o inp)t parameters !Ble't and Bright& -ith de'a)lt val)es !1*0 and 2*0&* I' the )ser
$alls the s)bro)tine -ith missing arg)ments+ the )nde'ined parameters -ill instead re$eive their de'a)lt
sub mysub T
myN G!eft, Gright OH]K%
G!eft \\H 1.5%
Gright \\H 4.5%
A dea! $ith G!eft and Gright here.
/he RYYVR operator is a 'an$y shorthand* /his:
G!eft \\H 1.5%
is e(a$tly the same as this:
G!eft H G!eft \\ 1.5%
2.1.&.#.2 )lo" Control
/he open!& ')n$tion here -ill attempt to open B'ilename 'or reading and atta$h B'ilehandle to it* I'
open!& 'ails in any -ay+ it ret)rns "LS6+ and "LS6 >,Red -ith die !& means that perl -ill eval)ate
the die!& ')n$tion to 'inish the logi$al eval)ation* It -onRt $omplete be$a)se e(e$)tion -ill die+ b)t the
end res)lt is $ode that is a$t)ally ;)ite readable*
open Nmy Gfi!ehand!e, Gfi!enameO
or die .cant open.%
2.1.&.#.3 Precedence
/he reason -e )sed RYYR in the 'irst e(ample and RorR in the se$ond e(ample is be$a)se the operators have
di''erent pre$eden$e+ and -e )sed the one -ith the pre$eden$e -e needed*
2.1.&.#.# *ssignment Precedence
Ghen -or%ing -ith an assignment+ )se RYYR and RXXR+ be$a)se they have a higher pre$eden$e than !and
are eval)ated be'ore& the assignment RVR* /he RorR and RandR operators have a pre$eden$e that is L>G6,
than an assignment+ meaning the assignment -o)ld o$$)r 'irst+ 'ollo-ed by any remaining RandR and RorR
my Gdefau!t H 5 \\ 1%
A defau!t is 1
my Gdefau!t H 5 or 1%
A defau!t is 5
/he se$ond !-rong& e(ample is e;)ivalent to this:
Nmy Gdefau!t H 5O or 1%
-hi$h -ill LG3S assign Bde'a)lt to the 'irst val)e and dis$ard the se$ond val)e*
2.1.&.#.& )lo" Control Precedence
Ghen )sing logi$al operators to per'orm 'lo- $ontrol+ )se RorR and RandR operators+ be$a)se they have
lo-er pre$eden$e than ')n$tions and other statements that 'orm the boolean inp)ts to the RorR or RandR
operator* /he RYYR and RXXR have higher pre$eden$e than ')n$tions and may e(e$)te be'ore the 'irst
')n$tion $all*
c!ose Gfh or die .;rrorBcou!d not c!ose.%
c!ose Gfh \\ die .;rrorB cou!d not c!ose.%
/he se$ond !-rong& e(ample is e;)ivalent to this:
c!ose NGfh \\ die .;rror.O%
-hi$h -ill LG3S eval)ate B'h as tr)e+ =676, die+ and $lose B'h* I' $lose!& 'ails+ the ret)rn val)e
is dis$arded+ and the program $ontin)es on its merry -ay*
It is al-ays possible to override pre$eden$e -ith parentheses+ b)t it is probably better to get in the habit
o' )sing the right operator 'or the right <ob*
2.1.&.#.+ Conditional !perator
/he $onditional operator mimi$s the $onditional testing o' an i'-else blo$%* /he $onditional operator
)ses three operands+ and is also $alled a trinary operator*
s it happens+ the $onditional operator is perlRs >=L3 trinary operator+ so people sometimes $all it the
trinary or ternary operator -hen they mean $onditional operator* s long as perl doesnRt add another
trinary operator+ its not a problem* It is even more rarely $alled the Z: operator*
/he $onditional operator has this 'orm:
my G@;#UL) H G+00L;-N1 X GV-LU;1 B GV-LU;4%
/his $an be re-ritten as an i'-else blo$% li%e this:
my G@;#UL)%
ifNG+00L;-N1O T
G@;#UL) H GV-LU;1
W e!se T
G@;#UL) H GV-LU;4
/he $onditional operator allo-s yo) to de$lare the variable and per'orm the assignment all in one short
line o' $ode*
=ote that B#>>L6=1+ B7L?61 and B7L?62 $an be repla$ed by any normal perl e(pression+
rather than being limited to a simple s$alar val)e* >ne interesting e(pression that yo) $o)ld repla$e
B7L?62 -ith is another $onditional operator+ e''e$tively allo-ing yo) to $reate a $hain o' i'-elsi'-
elsi'-else statements* "or e(ample:
my G@;#UL) H
G+00L;-N1 X GV-LU;1
B G+00L;-N4 X GV-LU;4
B G+00L;-N X GV-LU;
/he above e(ample is e;)ivalent to this mo)th')l:
my G@;#UL)%
ifNG+00L;-N1O T G@;#UL) H GV-LU;1 W
e!sifNG+00L;-N4O T G@;#UL) H GV-LU;4 W
e!sifNG+00L;-NO T G@;#UL) H GV-LU; W
e!sifNG+00L;-NIO T G@;#UL) H GV-LU;I W
e!es T G@;#UL) H GV-LU;J W
2.1.+ ,eferences
re'eren$e points to the variable to -hi$h it re'ers* It is %ind o' li%e a pointer in C+ -hi$h says Mthe
data I -ant is at this addressM* ?nli%e C+ yo) $annot man)ally alter the address o' a perl re'eren$e* 3o)
$an only $reate a re'eren$e to a variable that is visible 'rom yo)r $)rrent s$ope*
Create a re'eren$e by pla$ing a MLM in 'ront o' the variable:
my Gname H 79ohn7%
my Gage H I4%
my GnameKref H 8Gname%
my GageKref H 8Gage%
Perl -ill stringi'y a re'eren$e so that yo) $an print it and see -hat it is*
$arn .ageKref is 7GageKref7.%
D ageKref is 7#(-L-@N5*P14eRecO7 ...
/his tells yo) that BageHre' is a re'eren$e to a SCL, !-hi$h -e %no- is $alled Bage&* It also tells
yo) the address o' the variable to -hi$h -e are re'erring is 0(512e9e$*
3o) $annot re'eren$i'y a string* I*6* yo) $annot give perl a string+ s)$h as MSCL, !0(52925949&M
and have perl give yo) a re'eren$e to -hatever is at that address* Perl is pretty loosy goosey abo)t -hat
it -ill let yo) do+ b)t not even perl is so $ra@y as to give people $omplete a$$ess to the system memory*
3o) $an dere'eren$e a re'eren$e by p)tting an e(tra sigil !o' the appropriate type& in 'ront o' the
re'eren$e variable*
my Gname H 79ohn7%
my GrefKtoKname H 8Gname%
my GderefKname H GGrefKtoKname%
$arn GderefKname%
D 9ohn ...
,e'eren$es are interesting eno)gh that they get their o-n se$tion* #)t I introd)$e them here so that I
$an introd)$e a really $ool mod)le that )ses re'eren$es: 1ata::1)mper* 1ata::1)mper -ill ta%e a
re'eren$e to =3/4I=G and print o)t the thing to -hi$h it re'ers in a h)man readable 'orm*
/his does not seem very impressive -ith a re'eren$e to a s$alar:
my Gname H 79ohn7%
my GrefKtoKname H 8Gname%
$arn Dumper 8GrefKtoKname%
D GV-@1 H 879ohn7%
#)t this -ill be absol)tely essential -hen -or%ing -ith rrays and 4ashes*
2.1.- )ilehandles
S$alars $an store a 'ilehandle* "ile I> gets its o-n se$tion+ b)t I introd)$e it here to give a $omplete
pi$t)re o' -hat s$alars $an hold*
Given a s$alar that is )nde'ined !)ninitiali@ed&+ $alling open!& on that s$alar and a string 'ilename -ill
tell perl to open the 'ile spe$i'ied by the string+ and store the handle to that 'ile in the s$alar*
openNmy Gfh, 7Dout.t*t7O%
print Gfh .he!!o $or!d8n.%
print Gfh .this is simp!e fi!e $riting8n.%
/he s$alar $fh in the e(ample above holds the 'ilehandle to Mo)t*t(tM* Printing to the 'ilehandle
a$t)ally o)tp)ts the string to the 'ile*
/here is some magi$ going on there that I have not e(plained+ b)t that is a ;)i$% intro to s$alar
2.1.. Scalar ,eie"
S$alars $an store S/,I=GS+ =?:#6,S !'loats and ints&+ ,6"6,6=C6S+ and "IL64=1L6S*
Stringi'y: to $onvert something to a string 'ormat
=)mi'y: to $onvert something to a n)meri$ 'ormat
/he 'ollo-ing s$alars are interpreted as boolean "LS6:
integer 5, f!oat 5.5, string .5., string .., undef
ll other s$alar val)es are interpreted as boolean /,?6*
2.2 /rrays
rrays are pre$eded -ith an MatM sigil* /he MAM is a styli@ed MaM*
n array stores a b)n$h o' s$alars that are a$$essed via an integer inde(*
Perl arrays are >=6-1I:6=SI>=L >=L3* !1o =ot Pani$*&
/he 'irst element o' an array al-ays starts at [6,> !0&*
Ghen yo) re'er to an entire array+ )se the MAM sigil*
my ]numbers H /$ N Mero one t$o three O%
Ghen yo) inde( into the array+ the MAM $hara$ter $hanges to a MBM and the n)meri$ inde( is pla$ed in
s;)are bra$%ets*
my ]numbers H /$ N Mero one t$o three O%
my Gstring H GnumbersU4V%
$arn Gstring%
D t$o ...
/he length o' an array is not pre-de$lared* Perl a)tovivi'ies -hatever spa$e it needs*
my ]months%
A GmonthsU5V and GmonthsU4..IV are auto"i"ified
A and initia!iMed to undef
print Dumper 8]months%
D GV-@1 H U
D undef, A inde* 5 is undefined
D 79anuary7, A GmonthsU1V
D GT8GV-@1'DU5VW, A this is same as undef
D GT8GV-@1'DU5VW, A undef
D GT8GV-@1'DU5VW, A undef
D 7Cay7 A GmonthsUJV
D V%
I' yo) -ant to see i' yo) $an blo- yo)r memory+ try r)nning this pie$e o' $ode:
my ]memKhog%
A the array is fi!!ed $ith undefs
A e*cept the !ast entry, $hich is initia!iMed to 1
rrays $an store =3/4I=G that $an be stored in a s$alar
my ]<un,Kdra$er H N 7p!iers7, 1,1,1, 7L7, 7//7,
.1I, 6L11, 7yaba7, 7daba7 O%
=egative inde(es start 'rom the end o' the array and -or% ba$%-ards*
my ]co!ors H /$ N red green b!ue O%
my G!astHGco!orsU'1V%
$arn .!ast is 7G!ast7.%
D !ast is 7b!ue7 ...
2.2.1 scalar /0arra12
/o get ho- many elements are in the array+ )se Ms$alarM
my ]phonetic H /$ N a!pha bra"o char!ie de!ta O%
my G/uantity H sca!arN]phoneticO%
$arn G/uantity%
D I ...
Ghen yo) assign an entire array into a s$alar variable+ yo) -ill get the same thing+ b)t $alling s$alar!&
is m)$h more $lear*
my ]phonetic H /$ N a!pha bra"o char!ie O%
my G/uant H ]phonetic%
$arn G/uant%
D ...
/his is e(plained later in the Mlist $onte(tM se$tion*
2.2.2 push/0arra13 4IST2
?se p)sh!& to add elements onto the end o' the array !the highest inde(&* /his -ill in$rease the length
o' the array by the n)mber o' items added*
my ]groceries H /$ N mi!, bread O%
pushN]groceries, /$ N eggs bacon cheese OO%
print Dumper 8]groceries%
D GV-@1 H U
D 7mi!,7,
D 7bread7,
D 7eggs7,
D 7bacon7,
D 7cheese7
D V%
2.2.3 pop/0arra12
?se pop!& to get the last element o'' o' the end o' the array !the highest inde(&* /his -ill shorten the
array by one* /he ret)rn val)e o' pop!& is the val)e popped o'' o' the array*
my ]names H /$ N a!ice bob char!ie O%
my G!astKname H popN]namesO%
$arn .popped H G!astKname.%
print Dumper 8]names%
D popped H char!ie ...
D GV-@1 H U
D 7a!ice7,
D 7bob7
D V%
2.2.# shift/0arra12
?se shi't!& to remove one element 'rom the beginning.bottom o' an array !i*e* at inde( @ero&* ll
elements -ill be shi'ted 1>G= one inde(* /he array -ill be shorted by one*
/he ret)rn val)e is the val)e removed 'rom the array*
my ]curses H /$ N fee fie foe fum O%
my Gstart H shiftN]cursesO%
$arn Gstart%
$arn Dumper 8]curses%
D fee
D GV-@1 H U
D 7fie7,
D 7foe7,
D 7fum7
D V%
2.2.& unshift/ 0arra13 4IST2
)se )nshi't!& to add elements to the #6GI==I=G.#>//>: o' an array !i*e* at inde( [6,>&* ll the
other elements in the array -ill be shi'ted )p to ma%e room* /his -ill length the array by the n)mber o'
elements in LIS/*
my ]trees H /$ N pine map!e oa, O%
unshiftN]trees, 7birch7O%
$arn Dumper 8]trees%
D GV-@1 H U
D 7birch7, A inde* 5
D 7pine7, A o!d inde* 5, no$ 1
D 7map!e7, A 4
D 7oa,7 A
D V%
2.2.+ foreach /0arra12
?se 'orea$h to iterate thro)gh all the elements o' a list* Its 'ormal de'inition is:
L-+;L foreach V-@ NL&#)O +L0(^
/his is a $ontrol 'lo- str)$t)re that is $overed in more detail in the M$ontrol 'lo-M se$tion* /he 'orea$h
str)$t)re s)pports last+ ne(t+ and redo statements*
?se a simple 'orea$h loop to do something to ea$h element in an array:
my ]fruits H /$ N app!es oranges !emons pears O%
foreach my Gfruit N]fruitsO T
print .fruit is 7Gfruit78n.%
D fruit is 7app!es7
D fruit is 7oranges7
D fruit is 7!emons7
D fruit is 7pears7
1> =>/ 11 >, 16L6/6 6L6:6=/S /> = ,,3 #6I=G P,>C6SS61 I=
">,6C4 L>>P*
my ]numbers H /$ NMero one t$o threeO%
foreach my Gnum N]numbersO T
shiftN]numbersO ifNGnum e/ 7one7O%
print .num is 7Gnum78n.%
D num is 7Mero7
D num is 7one7
D num is 7three7
A noteB & de!eted 7Mero7, but & fai!ed to
A print out 7t$o7, $hich is sti!! part of array.
A +-D==
7, a$ts as an alias to the element o' the array itsel'* Changes to 7, propagate to $hanging the
my ]integers H N 4, 1I4, 6PI, P6IP O%
foreach my Gnum N]integersO T
print Dumper 8]integers%
D GV-@1 H U
D 14,
D 4I4,
D V%
2.2.- sort/0arra12
?se sort!& to sort an array alphabeti$ally* /he ret)rn val)e is the sorted version o' the array* /he array
passed in is le't )nto)$hed*
my ]fruit H /$ N pears app!es bananas oranges O%
my ]sortedKarray H sortN]fruitO%
print Dumper 8]sortedKarray %
DGV-@1 H U
D 7app!es7,
D 7bananas7,
D 7oranges7,
D 7pears7
D V%
Sorting a list o' n)mbers -ill sort them alphabeti$ally as -ell+ -hi$h probably is not -hat yo) -ant*
my ]scores H N 1555, 1, 43, 455, 3R, 1J5 O%
my ]sortedKarray H sortN]scoresO%
print Dumper 8]sortedKarray %
D GV-@1 H U
D 1555, A 17s
D 1, A 17s
D 1J5, A 17s
D 455,
D 43,
D 3R
D V%
/he sort!& ')n$tion $an also ta%e a $ode blo$% ! any pie$e o' $ode bet-een $)rly bra$es & -hi$h de'ines
ho- to per'orm the sort i' given any t-o elements 'rom the array* /he $ode blo$% )ses t-o global
variables+ Ba and Bb+ and de'ines ho- to $ompare the t-o entries*
/his is ho- yo) -o)ld sort an array n)meri$ally*
my ]scores H N 1555, 1, 43, 455, 3R, 1J5 O%
my ]sortedKarray H sort TGaQHDGbW N]scoresO%
print Dumper 8]sortedKarray %
D GV-@1 H U
D 1,
D 43,
D 3R,
D 1J5,
D 455,
D 1555
D V%
2.2.. reerse/0arra12
/he reverse!& ')n$tion ta%es a list and ret)rns an array in reverse order* /he last element be$omes the
'irst element* /he 'irst element be$omes the last element*
my ]numbers H re"erse N1555,1,43,455,3R,1J5O%
print Dumper 8]numbers %
D GV-@1 H U
D 1J5,
D 3R,
D 455,
D 43,
D 1,
D 1555
D V%
2.2.5 splice/0arra12
?se spli$e!& to add or remove elements into or o)t o' any inde( range o' an array*
sp!ice N -@@-> , 0FF#;) , L;NG)E , L&#) O%
/he elements in ,,3 starting at >""S6/ and going 'or L6=G/4 inde(es -ill be removed 'rom
,,3* ny elements 'rom LIS/ -ill be inserted at >""S6/ into ,,3*
my ]$ords H /$ N he!!o there O%
sp!iceN]$ords, 1, 5, 7out7O%
$arn <oinN. ., ]$ordsO%
D he!!o out there ...
2.2.16 $ndefined and $ninitiali%ed *rra1s
n array is initiali@ed as having no entries* /here'ore yo) $an test to see i' an array is initiali@ed by
$alling s$alar!& on it* /his is e;)ivalent to $alling de'ined!& on a s$alar variable* I' s$alar!& ret)rns 'alse
!i*e* integer 0&+ then the array is )ninitiali@ed*
I' yo) -ant to )ninitiali@e an array that $ontains data+ then yo) do =>/ -ant to assign it )nde' li%e yo)
-o)ld a s$alar* /his -o)ld 'ill the array -ith one element at inde( @ero -ith a val)e o' )nde'ined*
my ]array H undef% A :@0NG
/o $lear an array to its original )ninitiali@ed state+ assign an empty list to it* /his -ill $lear o)t any
entries+ and leave yo) -ith a $ompletely empty array*
my ]array H NO% A @&GE)
2.3 Hashes
4ashes are pre$eded -ith a per$ent sign sigil*
/he MEM is a styli@ed M%ey.val)eM pair*
hash stores a b)n$h o' s$alars that are a$$essed via a string inde( $alled a M%eyM
Perl hashes are >=6-1I:6=SI>=L >=L3* !1o =ot Pani$*&
/here is no order to the elements in a hash* !Gell+ there is+ b)t yo) sho)ld not )se a hash -ith an
ass)mption abo)t -hat order the data -ill $ome o)t*&
3o) $an assign any even n)mber o' s$alars to a hash* Perl -ill e(tra$t them in pairs* /he 'irst item -ill
be treated as the %ey+ and the se$ond item -ill be treated as the val)e*
Ghen yo) re'er to an entire hash+ )se the MEM sigil*
my Sinfo H /$ N name 9ohn age I4 O%
Ghen yo) loo% )p a %ey in the hash+ the MEM $hara$ter $hanges to a MBM and the %ey is pla$ed in $)rly
my Sinfo H /$ N name 9ohn age I4 O%
my Gdata H GinfoTnameW%
$arn Gdata%
D 9ohn ...
/he %eys o' a hash are not pre-de$lared* I' the %ey does not e(ist d)ring an SSIG=:6=/+ the %ey is
$reated and given the assigned val)e*
my Sin"entory%
print Dumper 8Sin"entory%
DGV-@1 H T
D 7bananas7 HD J,
D 7app!es7 HD I4,
D 7pears7 HD 13
D W%
I' the %ey does not e(ist d)ring a "6/C4+ the %ey is =>/ $reated+ and )nde' is ret)rned*
my Sin"entory%
my Gpeaches H Gin"entoryTpeachesW%
$arn .peaches is 7Gpeaches7.%
print Dumper 8Sin"entory%
D Use of uninitia!iMed "a!ue in concatenation
D peaches is 77 at ./test.p! !ine 1.
D GV-@1 H T
D 7app!es7 HD I4
D W%
2.3.1 exists / 7hash879e1: 2
?se e(ists!& to see i' a %ey e(ists in a hash* 3o) $annot simply test the val)e o' a %ey+ sin$e a %ey might
e(ist b)t store a val)e o' "LS6
my Spets H N catsHD4, dogsHD1 O%
un!essNe*istsNGpetsTfishWOO T
print .No fish here8n.%
Garning: d)ring m)lti-%ey loo%)p+ all the lo-er level %eys are a)tovivi'ied+ and only the last %ey has
e(ists!& tested on it* /his only happens i' yo) have a hash o' hash re'eren$es* ,e'eren$es are $overed
later+ b)t this is a M'eat)reM spe$i'i$ to e(ists!& that $an lead to very s)btle b)gs* =ote in the 'ollo-ing
e(ample+ -e e(pli$itly $reate the %ey M"loridaM+ b)t -e only test 'or the e(isten$e o' C:aineD-
ICState#irdD+ -hi$h has the side e''e$t o' $reating the %ey C:aineD in the hash*
my Sstateinfo%
if Ne*istsNGstateinfoTCaineW'DT#tate+irdWOO T
$arn .it e*ists.%
print Dumper 8Sstateinfo%
D GV-@1 H T
D 7F!orida7 HD T
D 7-bbre"iation7 HD 7FL7
D W,
D 7Caine7 HD TW
D W%
3o) m)st test ea$h level o' %ey individ)ally+ and b)ild yo)r -ay )p to the 'inal %ey loo%)p i' yo) do
not -ant to a)tovivi'y the lo-er level %eys*
my Sstateinfo%
if Ne*istsNGstateinfoTCaineWOO T
if Ne*istsNGstateinfoTCaineW'DT#tate+irdWOO
T $arn .it e*ists.% W
print Dumper 8Sstateinfo%
D GV-@1 H T
D 7F!orida7 HD T
D 7-bbre"iation7 HD 7FL7
D W%
2.3.2 delete / 7hash89e1: 2
?se delete to delete a %ey.val)e pair 'rom a hash* >n$e a %ey is $reated in a hash+ assigning )nde' to it
-ill %eep the %ey in the hash and -ill only assign the val)e to )nde'*
/he only -ay to remove a %ey.val)e pair 'rom a hash is -ith delete!&*
my Spets H N
print Dumper 8Spets%
D GV-@1 H T
D 7cats7 HD undef,
D 7dogs7 HD 1
D W%
2.3.3 9e1s/ ;hash 2
?se %eys!& to ret)rn a list o' all the %eys in a hash* /he order o' the %eys -ill be based on the internal
hashing algorithm )sed+ and sho)ld not be something yo)r program depends )pon* =ote in the e(ample
belo- that the order o' assignment is di''erent 'rom the order printed o)t*
my Spets H N
foreach my Gpet N,eysNSpetsOO T
print .pet is 7Gpet78n.%
D pet is 7cats7
D pet is 7dogs7
D pet is 7fish7
I' the hash is very large+ then yo) may -ish to )se the ea$h!& ')n$tion des$ribed belo-*
2.3.# alues/ ;hash 2
?se val)es!& to ret)rn a list o' all the val)es in a hash* /he order o' the val)es -ill mat$h the order o'
the %eys ret)rn in %eys!&*
my Spets H N
my ]petK,eys H ,eysNSpetsO%
my ]petK"a!s H "a!uesNSpetsO%
print Dumper 8]petK,eys%
print Dumper 8]petK"a!s%
D GV-@1 H U
D 7cats7,
D 7dogs7,
D 7fish7
D V%
D GV-@1 H U
D 4,
D 1,
D V%
I' the hash is very large+ then yo) may -ish to )se the ea$h!& ')n$tion des$ribed belo-*
2.3.& each/ ;hash 2
?se ea$h!& to iterate thro)gh ea$h %ey.val)e pair in a hash+ one at a time*
my Spets H N
$hi!eNmyNGpet,G/tyOHeachNSpetsOO T
print .petH7Gpet7, /tyH7G/ty78n.%
D petH7cats7, /tyH747
D petH7dogs7, /tyH717
D petH7fish7, /tyH77
6very $all to ea$h!& ret)rns the ne(t %ey.val)e pair in the hash* 'ter the last %ey.val)e pair is ret)rned+
the ne(t $all to ea$h!& -ill ret)rn an empty list+ -hi$h is boolean 'alse* /his is ho- the -hile loop is
able to loop thro)gh ea$h %ey.val)e and then e(it -hen done*
6very hash has one Mea$h iteratorM atta$hed to it* /his iterator is )sed by perl to remember -here it is in
the hash 'or the ne(t $all to ea$h!&*
Calling %eys!& on the hash -ill reset the iterator* /he list ret)rned by %eys!& $an be dis$arded*
1o not add %eys -hile iterating a hash -ith ea$h!&*
3o) $an delete %eys -hile iterating a hash -ith ea$h!&*
/he ea$h!& ')n$tion does not have to be )sed inside a -hile loop* /his e(ample )ses a s)bro)tine to $all
ea$h!& on$e and print o)t the res)lt* /he s)bro)tine is $alled m)ltiple times -itho)t )sing a -hile!&
my Spets H N
sub oneKtime T
A if ,ey is not defined,
A then eachNO must ha"e hit end of hash
ifNdefinedNGpetOO T
print .petH7Gpet7, /tyH7G/ty78n.%
W e!se T
print .end of hash8n.%
oneKtime% A cats
oneKtime% A dogs
,eysNSpetsO% A reset the hash iterator
oneKtime% A cats
oneKtime% A dogs
oneKtime% A fish
oneKtime% A end of hash
oneKtime% A cats
oneKtime% A dogs
D petH7cats7, /tyH747
D petH7dogs7, /tyH717
D petH7cats7, /tyH747
D petH7dogs7, /tyH717
D petH7fish7, /tyH77
D end of hash
D petH7cats7, /tyH747
D petH7dogs7, /tyH717
/here is only one iterator variable $onne$ted -ith ea$h hash+ -hi$h means $alling ea$h!& on a hash in a
loop that then $alls ea$h!& on the same hash another loop -ill $a)se problems* /he e(ample belo- goes
thro)gh the Epets hash and attempts to $ompare the ;)antity o' di''erent pets and print o)t their
my Spets H N
$hi!eNmyNGorigKpet,GorigK/tyOHeachNSpetsOO T
$hi!eNmyNGcmpKpet,GcmpK/tyOHeachNSpetsOO T
ifNGorigK/tyDGcmpK/tyO T
print .there are more GorigKpet .
..than GcmpKpet8n.%
W e!se T
print .there are !ess GorigKpet .
..than GcmpKpet8n.%
D there are more cats than dogs
D there are !ess cats than fish
D there are more cats than dogs
D there are !ess cats than fish
D there are more cats than dogs
D there are !ess cats than fish
D there are more cats than dogs
D there are !ess cats than fish
D ...
/he o)tside loop $alls ea$h!& and gets M$atsM* /he inside loop $alls ea$h!& and gets MdogsM* /he inside
loop $ontin)es+ $alls ea$h!& again+ and gets M'ishM* /he inside loop $alls ea$h!& one more time and gets
an empty list* /he inside loop e(its* /he o)tside loop $alls ea$h!& -hi$h $ontin)es -here the inside
loop le't o''+ namely at the end o' the list+ and ret)rns M$atsM* /he $ode then enters the inside loop+ and
the pro$ess repeats itsel' inde'initely*
>ne sol)tion 'or this ea$h!& limitation is sho-n belo-* /he inner loop $ontin)es to $all ea$h!& )ntil it
gets the %ey that mat$hes the o)ter loop %ey* /he inner loop m)st s%ip the end o' the hash !an
)nde'ined %ey& and $ontin)e the inner loop* /his also 'i(es a problem in the above e(ample in that -e
probably do not -ant to $ompare a %ey to itsel'*
my Spets H N
$hi!eNmyNGorigKpet,GorigK/tyOHeachNSpetsOO T
$hi!eN1O T
ne*t un!essNdefinedNGcmpKpetOO%
!ast ifNGcmpKpet e/ GorigKpetO%
ifNGorigK/tyDGcmpK/tyO T
print .there are more GorigKpet .
..than GcmpKpet8n.%
W e!se T
print .there are !ess GorigKpet .
..than GcmpKpet8n.%
D there are more cats than dogs
D there are !ess cats than fish
D there are !ess dogs than fish
D there are !ess dogs than cats
D there are more fish than cats
D there are more fish than dogs
I' yo) do not %no- the o)ter loop %ey+ either be$a)se its in someone elseRs $ode and they do not pass it
to yo)+ or some similar problem+ then the only other sol)tion is to $all %eys on the hash 'or all inner
loops+ store the %eys in an array+ and loop thro)gh the array o' %eys )sing 'orea$h* /he inner loop -ill
then not rely on the internal hash iterator val)e*
2.# 0ist -onte9t
List $onte(t is a $on$ept b)ilt into the grammar o' perl* 3o) $annot de$lare a Mlist $onte(tM in perl the
-ay yo) might de$lare an Aarray or Ehash* List $onte(t a''e$ts ho- perl e(e$)tes yo)r so)r$e $ode*
4ere is an e(ample*
my ]cart1H/$N mi!, bread butterO%
my ]cart4H/$N eggs bacon <uice O%
my ]chec,outKcounter H N ]cart1, ]cart4 O%
print Dumper 8]chec,outKcounter%
D GV-@1 H U
D 7mi!,7,
D 7bread7,
D 7butter7,
D 7eggs7,
D 7bacon7,
D 7<uice7
D V%
#asi$ally+ t-o people -ith gro$ery $arts+ A$art1 and A$art2+ p)lled )p to the A$he$%o)tH$o)nter and
)nloaded their $arts -itho)t p)tting one o' those separator bars in bet-een them* /he person behind the
A$he$%o)tH$o)nter has no idea -hose gro$eries are -hose*
6verything in list $onte(t gets red)$ed to an ordered series o' s$alars* /he original $ontainer that held
the s$alars is 'orgotten*
In the above e(ample the order o' s$alars is retained: mil%+ bread+ b)tter is the order o' s$alars in
A$art1 and the order o' the s$alars at the beginning o' A$he$%o)tH$o)nter* 4o-ever+ loo%ing at <)st
A$he$%o)tH$o)nter+ there is no -ay to %no- -here the $ontents o' A$art1 end and the $ontents o'
A$art2 begin* In 'a$t+ A$art1 might have been empty+ and all the $ontents o' A$he$%o)tH$o)nter
$o)ld belong to A$art2+ b)t there is no -ay to %no-*
Sometimes+ list $onte(t $an be e(tremely handy* Ge have )sed list $onte(t repeatedly to initiali@e
arrays and hashes and it -or%ed as -e -o)ld int)itively e(pe$t:
my Spets H N fishHD, catsHD4, dogsHD1 O%
my ]cart1 H /$N mi!, bread eggsO%
/he initial val)es 'or the hash get $onverted into an ordered list o' s$alars
N 7fish7, , 7cats7, 4, 7dogs7, 1 O
/hese s$alars are then )sed in list $onte(t to initiali@e the hash+ )sing the 'irst s$alar as a %ey and the
'ollo-ing s$alar as its val)e+ and so on thro)gho)t the list*
List $onte(t applies anytime data is passed aro)nd in perl* S$alars+ arrays+ and hashes are all a''e$ted by
list $onte(t* In the e(ample belo-+ Aho)se is intended to $ontain a list o' all the items in the ho)se*
4o-ever+ be$a)se the Epets hash -as red)$ed to s$alars in list $onte(t+ the val)es 2+2+1 are
disasso$iated 'rom their %eys* /he Aho)se variable is not very )se')l*
my Spets H N fishHD, catsHD4, dogsHD1 O%
my ]refrigeratorH/$Nmi!, bread eggsO%
my ]houseHN7couch7,Spets,]refrigerator,7chair7O%
print Dumper 8]house%
DGV-@1 H U
D 7couch7,
D 7cats7,
D 4,
D 7dogs7,
D 1,
D 7fish7,
D ,
D 7mi!,7,
D 7bread7,
D 7eggs7,
D 7chair7
D V%
/here are times -hen list $onte(t on a hash does ma%e sense*
my SencryptHNtan,HD7turt!e7,bomberHD7eag!e7O%
my SdecryptHre"erseNSencryptO %
print Dumper 8Sdecrypt%
D GV-@1 H T
D 7eag!e7 HD 7bomber7,
D 7turt!e7 HD 7tan,7
D W%
/he Een$rypt hash $ontains a hash loo% )p to en$rypt plainte(t into $ypherte(t* nytime yo) -ant to
)se the -ord MbomberM+ yo) a$t)ally send the -ord MeagleM* /he de$ryption is the opposite* nytime
yo) re$eive the -ord MeagleM yo) need to translate that to the -ord MbomberM*
?sing the Een$rypt hash to per'orm de$ryption -o)ld re;)ire a loop that $alled ea$h!& on the Een$rypt
hash+ looping )ntil it 'o)nd the val)e that mat$hed the -ord re$eived over the radio* /his $o)ld ta%e too
Instead+ be$a)se there is no overlap bet-een %eys and val)es+ !t-o di''erent -ords donRt en$rypt to the
same -ord&+ -e $an simply treat the Een$rypt hash as a list+ $all the array reverse!& ')n$tion on it+
-hi$h 'lips the list aro)nd 'rom end to end+ and then store that reversed list into a Ede$rypt hash*
2.) (eferences
,e'eren$es are a thing that re'er !point& to something else*
/he Msomething elseM is $alled the Mre'erentM+ the thing being pointed to*
/a%ing a re'eren$e and )sing it to a$$ess the re'erent is $alled Mdere'eren$ingM*
good real--orld e(ample is a driverRs li$ense* 3o)r li$ense MpointsM to -here yo) live be$a)se it lists
yo)r home address* 3o)r li$ense is a Mre'eren$eM* /he Mre'erentM is yo)r home* nd i' yo) have
'orgotten -here yo) live+ yo) $an ta%e yo)r li$ense and Mdere'eren$ingM it to get yo)rsel' home*
It is possible that yo) have roommates+ -hi$h -o)ld mean m)ltiple re'eren$es e(ist to point to the
same home* #)t there $an only be one home per address*
In perl+ re'eren$es are stored in s$alars* 3o) $an $reate a re'eren$e by $reating some data !s$alar+ array+
hash& and p)tting a MLM in 'ront o' it*
my ShomeH N
my G!icenseKforKa!ice H 8Shome%
my G!icenseKforKbob H 8Shome%
li$e and #ob are roommates and their li$enses are re'eren$es to the same Ehome* /his means that
li$e $o)ld bring in a b)n$h o' ne- pets and #ob $o)ld eat the bread o)t o' the re'rigerator even
tho)gh li$e might have been the one to p)t it there* /o do this+ li$e and #ob need to dere'eren$e
their li$enses and get into the original Ehome hash*
G TG!icenseKforKa!iceW TdogsW FH J%
de!eteNG TG!icenseKforKbobW Tmi!,WO%
print Dumper 8Shome%
D GV-@1 H T
D 7eggs7 HD 14,
D 7cats7 HD 4,
D 7bread7 HD 4,
D 7dogs7 HD R,
D 7fish7 HD
D W%
2.&.1 Named ,eferents
re'erent is any original data str)$t)re: a s$alar+ array+ or hash* #elo-+ -e de$lare some named
re'erents: age+ $olors+ and pets*
my Gage H I4%
my ]co!ors H /$N red green b!ue O%
my SpetsHNfishHD,catsHD4,dogsHD1O%
2.&.2 ,eferences to Named ,eferents
re'eren$e points to the re'erent* /o ta%e a re'eren$e to a named re'erent+ p)t a MLM in 'ront o' the
named re'erent*
my GrefKtoKage H 8Gage%
my GrK4Kco!ors H 8]co!ors%
my GrKpets H 8Spets%
2.&.3 'ereferencing
/o dere'eren$e+ pla$e the re'eren$e in $)rly bra$es and pre'i( it -ith the sigil o' the appropriate type*
/his -ill give a$$ess to the entire original re'erent*
GTGrefKtoKageWFF% A happy birthday
my ScopyKofKpets H STGrKpetsW%
print .age is 7Gage78n.%
D age is 7I7
I' there is no ambig)ity in dere'eren$ing+ the $)rly bra$es are not needed*
GGrefKtoKage FF% A another birthday
print .age is 7Gage78n.%
D age is 7II7
It is also possible to dere'eren$e into an array or hash -ith a spe$i'i$ inde( or %ey*
my ]co!ors H /$N red green b!ue O%
my SpetsHNfishHD,catsHD4,dogsHD1O%
my GrKco!ors H 8]co!ors% my GrKpets H 8Spets%
GTGrKpetsW TdogsW FH J%
GTGrKco!orsWU1V H 7ye!!o$7%
print Dumper 8]co!ors% print Dumper 8Spets%
D GV-@1 H U
7ye!!o$7, A green turned to ye!!o$
GV-@1 H T
7cats7 HD 4,
7dogs7 HD R, A J ne$ dogs
7fish7 HD
#e$a)se array and hash re'erents are so $ommon+ perl has a shorthand notation 'or inde(ing into an
array or loo%ing )p a %ey in a hash )sing a re'eren$e* /a%e the re'eren$e+ 'ollo- it by M-IM+ and then
'ollo- that by either M\inde(]M or MC%eyDM* /his:
GTGrKpetsW TdogsW FH J%
GTGrKco!orsWU1V H 7ye!!o$7%
is e(a$tly the same as this:
GrKpets'DTdogsW FH J%
GrKco!ors'DU1V H 7ye!!o$7%
2.&.# *non1mous ,eferents
4ere are some re'erents named age+ $olors+ and pets* 6a$h named re'erent has a re'eren$e to it as -ell*
my Gage H I4%
my ]co!ors H /$N red green b!ue O%
my SpetsHNfishHD,catsHD4,dogsHD1O%
my GrKage H 8Gage%
my GrKco!ors H 8]co!ors%
my GrKpets H 8Spets%
It is also possible in perl to $reate an =>=3:>?S ,6"6,6=/* n anonymo)s re'erent has no
name 'or the )nderlying data str)$t)re and $an only be a$$essed thro)gh the re'eren$e*
/o $reate an anonymo)s array re'erent+ p)t the $ontents o' the array in s;)are bra$%ets*
/he s;)are bra$%ets -ill $reate the )nderlying array -ith no name+ and ret)rn a re'eren$e to that
)nnamed array*
my Gco!orsKref H U 7red7, 7green7, 7b!ue7 V%
print Dumper Gco!orsKref%
D GV-@1 H U
D 7red7,
D 7green7,
D 7b!ue7
D V%
/o $reate an anonymo)s hash re'erent+ p)t the $ontents o' the hash in $)rly bra$es* /he $)rly bra$es
-ill $reate the )nderlying hash -ith no name+ and ret)rn a re'eren$e to that )nnamed hash*
my GpetsKref H T fishHD,catsHD4,dogsHD1 W%
print Dumper GpetsKref%
D GV-@1 H T
D 7cats7 HD 4,
D 7dogs7 HD 1,
D 7fish7 HD
D W%
=ote that B$olorsHre' is a re'eren$e to an array+ b)t that array has no name to dire$tly a$$ess its data*
3o) m)st )se B$olorsHre' to a$$ess the data in the array* Li%e-ise+ BpetsHre' is a re'eren$e to a hash+
b)t that hash has no name to dire$tly a$$ess its data* 3o) m)st )se BpetsHre' to a$$ess the data in the
2.&.& Complex 'ata Structures
rrays and hashes $an only store s$alar val)es* #)t be$a)se s$alars $an hold re'eren$es+ $omple( data
str)$t)res are no- possible* ?sing re'eren$es is one -ay to avoid the problems asso$iated -ith list
$onte(t* 4ere is another loo% at the ho)se e(ample+ b)t no- )sing re'eren$es*
my Spets H N fishHD, catsHD4, dogsHD1 O%
my ]refrigeratorH/$Nmi!, bread eggsO%
my GhouseHT
print Dumper Ghouse%
D GV-@1 H T
D 7pets7 HD T
D 7cats7 HD 4,
D 7dogs7 HD 1,
D 7fish7 HD
D W,
D 7refrigerator7 HD U
D 7mi!,7,
D 7bread7,
D 7eggs7
D W%
/he Bho)se variable is a re'eren$e to an anonymo)s hash+ -hi$h $ontains t-o %eys+ MpetsM and
Mre'rigeratorM* /hese %eys are asso$iated -ith val)es that are re'eren$es as -ell+ one a hash re'eren$e
and the other an array re'eren$e*
1ere'eren$ing a $omple( data str)$t)re $an be done -ith the arro- notation or by en$losing the
re'eren$e in $)rly bra$es and pre'i(ing it -ith the appropriate sigil*
A -!ice added more canines
A +ob dran, a!! the mi!,
2.).).1 /utoiification
Perl a)tovivi'ies any str)$t)re needed -hen assigning or 'et$hing 'rom a re'eren$e* /he a)tovivi'ied
re'erents are anonymo)s* Perl -ill ass)me yo) %no- -hat yo) are doing -ith yo)r str)$t)res* In the
e(ample belo-+ -e start o)t -ith an )nde'ined s$alar $alled Bs$al* Ge then 'et$h 'rom this )nde'ined
s$alar+ as i' it -ere a re'eren$e to an array o' a hash o' an array o' a hash o' an array* Perl a)tovivi'ies
everything )nder the ass)mption that that is -hat yo) -anted to do*
my Gsca!%
my G"a! H
print Dumper Gsca!%
D GV-@1 H U
D undef,
D 7some,ey7 HD U
D 7other,ey7 HD UV
D V%
I' this is =>/ -hat yo) -ant to do+ $he$% 'or the e(isten$e o' ea$h hash %ey and $he$% that the array
$ontains at least eno)gh array entries to handle the given inde(*
2.).).2 +ultidimensional /rrays
Perl implements m)ltidimensional arrays )sing one-dimensional arrays and re'eren$es*
my Gmda%
forNmy GiH5%GiQ4%GiFFOT
forNmy G<H5%G<Q4%G<FFO T
forNmy G,H5%G,Q4%G,FFOT
.ro$HGi, co!HG<, depthHG,.%
print Dumper Gmda%
D GV-@1 H U
D 7ro$H5, co!H5, depthH57,
D 7ro$H5, co!H5, depthH17
D V,
D 7ro$H5, co!H1, depthH57,
D 7ro$H5, co!H1, depthH17
D V,
D 7ro$H1, co!H5, depthH57,
D 7ro$H1, co!H5, depthH17
D V,
D 7ro$H1, co!H1, depthH57,
D 7ro$H1, co!H1, depthH17
D V%
2.).).3 Deep -loning% Deep -opy
I' yo) need to $reate an entirely separate b)t identi$al $lone o' a $omple( data str)$t)re+ )se the
Storable*pm perl mod)le* Storable $omes standard -ith perl 8*5* I' yo) donRt have 8*5 installed+
$onsider an )pgrade* >ther-ise+ read the se$tion abo)t CP= later in this do$)ment+ do-nload
Storable 'rom CP=+ and install*
/hen )se Storable in yo)r perl $ode+ indi$ating yo) -ant to import the RnstoreR+ Rd$loneR+ and RretrieveR
s)bro)tines* /he R)seR statement is e(plained later in this do$)ment as -ell+ 'or no-+ it isnRt that
/he Rd$loneR s)bro)tine ta%es a re'eren$e to any %ind o' data str)$t)re and ret)rns a re'eren$e to a deep
$loned version o' that data str)$t)re*
use #torab!e /$Nnstore dc!one retrie"eO%
my Gsca!%
A Gt$in is an identica! c!one of Gsca!
my Gt$in H dc!one Gsca!%
2.).).# Data !ersistence
/he Storable*pm mod)le also $ontains t-o s)bro)tines 'or storing the $ontents o' any perl data
str)$t)re to a 'ile and retrieving it later*
use #torab!e /$Nnstore dc!one retrie"eO%
my Gsca!%
nstore NGsca!, 7fi!ename7O%
A e*it, reboot computer, and restart script
my Gre"i"ed H retrie"eN7fi!ename7O%
2.&.+ Stringification of ,eferences
Perl -ill stringi'y a re'eren$e i' yo) try to do anything string-li%e -ith it+ s)$h as print it*
my Greferent H I4%
my Greference H 8Greferent%
$arn .reference is 7Greference7.%
D reference is 7#(-L-@N5*P14eRecO7 ...
#)t perl -ill not allo- yo) to $reate a string and attempt to t)rn it into a re'eren$e*
my Greference H 7#(-L-@N5*P14eRecO7%
my G"a!ue H GGreference%
D (an7t use string N.#(-L-@N5*P14eRecO.O as
D a #(-L-@ ref $hi!e .strict refs. in use
/)rning stri$t o'' only gives yo) )nde'*
no strict%
my Greference H 7#(-L-@N5*P14eRecO7%
my G"a!ue H GGreference%
$arn ."a!ue not defined. un!essNdefinedNG"a!ueOO%
$arn ."a!ue is 7G"a!ue78n.%
D "a!ue not defined
D Use of uninitia!iMed "a!ue in concatenation
#e$a)se a re'eren$e is al-ays a string that loo%s something li%e MSCL,!0(512e9e$&M+ it -ill
eval)ate tr)e -hen treated as a boolean+ even i' the val)e to -hi$h it points is 'alse*
2.&.- The ref/2 function
/he re'!& ')n$tion ta%es a s$alar and ret)rns a string indi$ating -hat %ind o' re'erent the s$alar is
re'eren$ing* I' the s$alar is not a re'eren$e+ re'!& ret)rns 'alse !an empty string&*
my Gtemp H 8I4%
my Gstring H refNGtempO%
$arn .string is 7Gstring7.%
D string is 7#(-L-@7
4ere -e $all re'!& on several types o' variable:
sub $hatKisKit T
my NGsca!arOH]K%
my Gstring H refNGsca!arO%
print .string is 7Gstring78n.%
$hatKisKitN 87he!!o7 O%
$hatKisKitN U1,4,V O%
$hatKisKitN TcatsHD4W O%
$hatKisKitN I4 O%
D string is 7#(-L-@7
D string is 7-@@->7
D string is 7E-#E7
D string is 77
=ote that this is li%e stringi'i$ation o' a re'eren$e e($ept -itho)t the address being part o' the string*
Instead o' SCL,!0(512e9e$&+ its <)st SCL,* lso note that i' yo) stringi'y a non-re'eren$e+ yo)
get the s$alar val)e* #)t i' yo) $all re'!& on a nonre'eren$e+ yo) get an empty string+ -hi$h is al-ays
3 Control )lo"
Standard statements get e(e$)ted in se;)ential order in perl*
my Gname H 79ohn #mith7%
my Ggreeting H .Ee!!o, Gname8n.%
print Ggreeting%
Control 'lo- statements allo- yo) to alter the order o' e(e$)tion -hile the program is r)nning*
ifN Gprice HH 5 O T
print .Free +eer=8n.%
Perl s)pports the 'ollo-ing $ontrol 'lo- str)$t)res:
L-+;L is an optiona! name that identifies the
A contro! f!o$ structure.
A &t is a bare$ord identifier fo!!o$ed by a co!on.
A e*amp!eHHD C>KN-C;B
#&NGL;K#)-);C;N) HHD a sing!e per! statement
A N0) inc!uding the semico!on.
A print .he!!o8n.
+L0(^ HHD Mero or more statements contained
A in cur!y braces T print .hi.% W
L-+;L +L0(^
L-+;L +L0(^ continue +L0(^
A +00L HHD boo!ean Nsee boo!ean section abo"eO
#&NGL;K#)-);C;N) if N+00LO%
if N+00LO +L0(^
if N+00LO +L0(^ e!se +L0(^
if N+00LO +L0(^ e!sif N+00LO +L0(^ e!sif NO...
if N+00LO +L0(^ e!sif N+00LO +L0(^ ... e!se +L0(^
un!ess N+00LO +L0(^
un!ess N+00LO +L0(^ e!se +L0(^
un!ess N+00LO +L0(^ e!sif N+00LO +L0(^ e!sif NO...
un!ess N+00LO +L0(^ e!sif N+00LO +L0(^ ... e!se
L-+;L $hi!e N+00LO +L0(^
L-+;L $hi!e N+00LO +L0(^ continue +L0(^
L-+;L unti! N+00LO +L0(^
L-+;L unti! N+00LO +L0(^ continue +L0(^
A &N&), );#), (0N) are a!! e*pressions
A &N&) is an initia!iMation e*pression
A &N&) is e"a!uated once prior to !oop entry
A );#) is +00L;-N e*pression that contro!s !oop e*it
A );#) is e"a!uated each time after
A +L0(^ is e*ecuted
A (0N) is a continuation e*pression
A (0N) is e"a!uated each time );#) is e"a!uated )@U;
L-+;L for N &N&)% );#)% (0N) O +L0(^
A L&#) is a !ist of sca!ars, see arrays and
A !ist conte*t sections !ater in te*t
L-+;L foreach NL&#)O +L0(^
L-+;L foreach V-@ NL&#)O +L0(^
L-+;L foreach V-@ NL&#)O +L0(^ continue +L0(^
3.1 0a2els
Labels are al-ays optional* label is an identi'ier 'ollo-ed by a $olon*
label is )sed to give its asso$iated $ontrol 'lo- str)$t)re a name*
Inside a #L>CJ o' a $ontrol 'lo- str)$t)re+ yo) $an $all
I' the str)$t)re has a L#6L+ yo) $an $all
ne*t L-+;L%
!ast L-+;L%
redo L-+;L%
I' no label is given to ne(t+ last+ or redo+ then the $ommand -ill operate on the inner-most $ontrol
str)$t)re* I' a label is given+ then the $ommand -ill operate on the $ontrol str)$t)re given*
3.2 last 0/B&0<
/he last $ommand goes to the end o' the entire $ontrol str)$t)re* It does not e(e$)te any $ontin)e blo$%
i' one e(ists*
3.3 ne9t 0/B&0<
/he ne(t $ommand s%ips the remaining #L>CJ* i' there is a $ontin)e blo$%+ e(e$)tion res)mes there*
'ter the $ontin)e blo$% 'inishes+ or i' no $ontin)e blo$% e(ists+ e(e$)tion starts the ne(t iteration o'
the $ontrol $onstr)$t i' it is a loop $onstr)$t*
3.# redo 0/B&0<
/he redo $ommand s%ips the remaining #L>CJ* It does not e(e$)te any $ontin)e blo$% !even i' it
e(ists&* 6(e$)tion then res)mes at the start o' the $ontrol str)$t)re -itho)t eval)ating the $onditional
# Pac9ages and Namespaces and 4exical Scoping
#.1 !ac=age Declaration
Perl has a pa$%age de$laration statement that loo%s li%e this:
pac,age N-C;#P-(;%
/his pa$%age de$laration indi$ates that the rest o' the en$losing blo$%+ s)bro)tine+ eval+ or 'ile belongs
to the namespa$e given by =:6SPC6*
/he standard -arnings+ stri$tness+ and 1ata::1)mper are atta$hed to the namespa$e in -hi$h they -ere
t)rned on -ith M)se -arningsFM et$* nytime yo) de$lare a ne- pa$%age namespa$e+ yo) -ill -ant to
M)seM these again*
pac,age #ome0therPac,age%
use $arnings% use strict% use DataBBDumper%
ll perl s$ripts start -ith an implied de$laration o':
pac,age main%
3o) $an a$$ess pa$%age variables -ith the appropriate sigil+ 'ollo-ed by the pa$%age name+ 'ollo-ed
by a do)ble $olon+ 'ollo-ed by the variable name* /his is $alled a pa$%age K?LI"I61 variable
meaning the pa$%age name is e(pli$itly stated*
I' yo) )se an ?=K?LI"I61 variable in yo)r $ode+ perl ass)mes it is in the the most re$ently
de$lared pa$%age namespa$e that -as de$lared*
Ghen yo) have stri$t-ness t)rned on+ there are t-o -ays to $reate and )se pa$%age variables:
1& ?se the ')lly pa$%age ;)ali'ied name every-here in yo)r $ode:
A can use "ariab!e $ithout dec!aring it $ith 7my7
$arn .)he "a!ue is 7GsomeKpac,ageBBans$er78n.%
#.2 Declaring !ac=age 'aria2les >ith our
2& ?se Mo)rM to de$lare the variable*
pac,age thisKpac,age%
our GnameH79ohn7%
$arn .name is 7Gname7.%
?sing Mo)rM is the pre'erred method* 3o) m)st have perl 8*9*0 or later 'or Mo)rM de$larations*
/he di''eren$e bet-een the t-o methods is that al-ays )sing pa$%age ;)ali'ied variable names means
yo) do =>/ have to de$lare the pa$%age yo) are in* 3o) $an $reate variables in =3 namespa$e yo)
-ant+ -itho)t ever having to de$lare the namespa$e e(pli$itly* 3o) $an even de$lare variables in
someone elseRs pa$%age namespa$e* /here is no restri$tions in perl that prevent yo) 'rom doing this*
/o en$o)rage programmers to play ni$e -ith ea$h otherRs namespa$es+ the Mo)rM ')n$tion -as $reated*
1e$laring a variable -ith Mo)rM -ill $reate the variable in the $)rrent namespa$e* I' the namespa$e is
other than MmainM+ then yo) -ill need to de$lare the pa$%age namespa$e e(pli$itly* 4o-ever+ on$e a
pa$%age variable is de$lared -ith Mo)rM+ the ')lly pa$%age ;)ali'ied name is =>/ re;)ired+ and yo) $an
re'er to the variable <)st on its variable name+ as e(ample !2& above re'ers to the Bname pa$%age
Ge do not 476 to )se the Mo)rM short$)t even i' -e )sed it to de$lare it* /he Mo)rM de$laration is a
shorthand 'or de$laring a pa$%age variable* >n$e the pa$%age variable e(ists+ -e $an a$$ess it any -ay
-e -ish*
pac,age Eogs%
our Gspea, H 7oin,7%
$arn .EogsBBspea, is 7GEogsBBspea,7.%
D EogsBBspea, is 7oin,7 ...
#.3 !ac=age 'aria2les inside a 0e9ical $cope
Ghen yo) de$lare a pa$%age inside a $ode blo$%+ that pa$%age namespa$e de$laration remains in e''e$t
)ntil the end o' the blo$%+ at -hi$h time+ the pa$%age namespa$e reverts to the previo)s namespa$e*
pac,age Eogs%
our Gspea, H 7oin,7%
T A #)-@) 0F (0D; +L0(^
pac,age Eeifers%
our Gspea, H 7moo7%
W A ;ND 0F (0D; +L0(^
$arn .spea, is 7Gspea,7.%
D spea, is 7oin,7 ...
/he 4ei'ers namespa$e still e(ists+ as does all the variables that -ere de$lared in that namespa$e* Its
<)st that o)tside the $ode blo$%+ the Mo)r 4ei'ersFM de$laration has -orn o''+ and -e no- have to )se a
')lly pa$%age ;)ali'ied name to get to the variables in 4ei'ers pa$%age* /his M-earing o''M is a ')n$tion
o' the $ode blo$% being a Mle(i$al s$opeM and a pa$%age de$laration only lasts to the end o' the $)rrent
le(i$al s$ope* /he pa$%age variables de$lared inside the $ode blo$% Ms)rviveM a'ter the $ode blo$% ends*
pac,age Eeifers%
our Gspea, H 7moo7%
print .EeifersBBspea, is 7GEeifersBBspea,78n.%
D EeifersBBspea, is 7moo7
#.# 0e9ical $cope
Le(i$al re'ers to -ords or te(t* le(i$al s$ope e(ists -hile e(e$)tion ta%es pla$e inside o' a parti$)lar
$h)n% o' so)r$e $ode* In the above e(amples+ the Mpa$%age 4ei'ersFM only e(ists inside the $)rly bra$es
o' the so)r$e $ode* >)tside those $)rly bra$es+ the pa$%age de$laration has gone o)t o' s$ope+ -hi$h is
a te$hni$al -ay o' saying its M-orn o''M* S$ope re'ers to vision+ as in teles$ope* Githin a le(i$al s$ope+
things that have le(i$al limitations !s)$h as a pa$%age de$laration& are only MvisibleM inside that le(i$al
So Mle(i$al s$opeM re'ers to anything that is visible or has an e''e$t only -ithing a $ertain bo)ndary o'
the so)r$e te(t or so)r$e $ode* /he easiest -ay to demonstrate le(i$al s$oping is le(i$al variables+ and
to sho- ho- le(i$al variables di''er 'rom Mo)rM variables*
#.) 0e9ical 'aria2les
Le(i$al variables are de$lared -ith the ^myS %ey-ord* Le(i$al variables de$lared inside a le(i$al s$ope
do not s)rvive o)tside the le(i$al s$ope*
no $arnings%
no strict%
my Gspea, H 7moo7%
$arn .spea, is 7Gspea,78n.%
D spea, is 77
/he le(i$al variable MBspea%M goes o)t o' s$ope at the end o' the $ode blo$% !at the MDM $hara$ter&+ so it
does not e(ist -hen -e try to print it o)t a'ter the blo$%* Ge had to t)rn -arnings and stri$t o'' <)st to
get it to $ompile be$a)se -ith -arnings and stri$t on+ perl -ill %no- Bspea% does not e(ist -hen yo)
attempt to print it+ so it -ill thro- an e($eption and ;)it*
Le(i$ally s$oped variables have three main 'eat)res:
1& Le(i$al variables do not belong to any pa$%age namespa$e+ so yo) $annot pre'i( them -ith a
pa$%age name* /he e(ample belo- sho-s that ^my B$ntS is not the same as the ^main::$ntS:
no $arnings%
pac,age main%
my GcntH7& am <ust a !e*ica!7%
$arn .mainBBcnt is 7GmainBBcnt7.%
D mainBBcnt is 77
2& Le(i$al variables are only dire$tly a$$essible 'rom the point -here they are de$lared to the end o' the
nearest en$losing blo$%+ s)bro)tine+ eval+ or 'ile*
no strict%
my GsomeK!e* H 7& am !e*7%
$arn .someK!e* is 7GsomeK!e*7.%
D someK!e* is 77
2& Le(i$al variables are s)b<e$t to Mgarbage $olle$tionM at the end o' s$ope* I' nothing is )sing a le(i$al
variable at the end o' s$ope+ perl -ill remove it 'rom its memory* 6very time a variable is de$lared -ith
MmyM+ it is $reated dynami$ally+ d)ring e(e$)tion* /he lo$ation o' the variable -ill $hange ea$h time*
=ote in the e(ample belo-+ -e $reate a ne- Ble(Hvar ea$h time thro)gh the loop+ and Ble(Hvar is at a
di''erent address ea$h time*
my ]cupboard%
for N1 .. JO T
my G!e*K"ar H7canned goods7%
my G!e*Kref H 8G!e*K"ar%
pushN]cupboard, G!e*KrefO%
print .G!e*Kref8n.%
D #(-L-@N5*P14e335O
D #(-L-@N5*P14eRcPO
D #(-L-@N5*P14eRe5O
D #(-L-@N5*P1R4IcPO
D #(-L-@N5*P1IcfRIO
Le(i$al variables are <)st plain good* /hey generally %eep yo) 'rom stepping on someone elseRs toes*
/hey also %eep yo)r data more private than a pa$%age variable* Pa$%age variables are permanent+ never
go o)t o' s$ope+ never get garbage $olle$ted+ and are a$$essible 'rom anyoneRs s$ript*
#.* ?ar2age -ollection
Ghen a le(i$al variable goes o)t o' s$ope+ perl -ill $he$% to see i' anyone is )sing that variable+ and i'
no one is )sing it+ perl -ill delete that variable and 'ree )p memory*
/he 'reed )p memory is not ret)rned to the system+ rather the 'reed )p memory is )sed 'or possible
de$larations o' ne- le(i$ally s$oped variables that $o)ld be de$lared later in the program*
/his means that yo)r program -ill never get smaller be$a)se o' le(i$al variables going o' o' s$ope*
>n$e the memory is allo$ated 'or perl+ it remains )nder perlRs <)risdi$tion* #)t perl $an )se garbage
$olle$ted spa$e 'or other le(i$al variables*
I' a le(i$al variable is a re'erent o' another variable+ then the le(i$al -ill not be garbage $olle$ted -hen
it goes o)t o' s$ope*
no strict%
my GreferringK"ar%
my GsomeK!e* H 7& am !e*7%
$arn .someK!e* is 7GsomeK!e*7.%
$arn .referring "ar refers to 7GGreferringK"ar7.%
D someK!e* is 77
D referring "ar refers to 7& am !e*7
Ghen the le(i$al BsomeHle( -ent o)t o' s$ope+ -e $o)ld no longer a$$ess it dire$tly* #)t sin$e
Bre'erringHvar is a re'eren$e to BsomeHle(+ then BsomeHle( -as never garbage $olle$ted+ and it retained
its val)e o' MI am le(M* /he data in BsomeHle( -as still a$$essible thro)gh re'erringHvar*
=ote that the named variable BsomeHle( -ent o)t o' s$ope at the end o' the $ode blo$% and $o)ld not
be a$$essed by name*
#.+.1 ,eference Count <arbage Collection
Perl )ses re'eren$e $o)nt based garbage $olle$tion* It is r)dimentary re'eren$e $o)nting+ so $ir$)lar
re'eren$es -ill not get $olle$ted even i' nothing points to the $ir$le* /he e(ample belo- sho-s t-o
variables that re'er to ea$h other b)t nothing re'ers to the t-o variables* Perl -ill not garbage $olle$t
these variables even tho)gh they are $ompletely ina$$essible by the end o' the $ode blo$%*
my NGfirst,G!astO%
#.+.2 <arbage Collection and Subroutines
Garbage $olle$tion does not rely stri$tly on re'eren$es to a variable to determine i' it sho)ld be garbage
$olle$ted* I' a s)bro)tine )ses a le(i$al variable+ then that variable -ill not be garbage $olle$ted as long
as the s)bro)tine e(ists*
S)bro)tines that )se a le(i$al variable de$lared o)tside o' the s)bro)tine de$laration are $alled
In the e(ample belo-+ the le(i$al variable+ B$nt+ is de$lared inside a $ode blo$% and -o)ld normally get
garbage $olle$ted at the end o' the blo$%* 4o-ever+ t-o s)bro)tines are de$lared in that same $ode
blo$% that )se B$nt+ so B$nt is not garbage $olle$ted* Sin$e B$nt goes o)t o' s$ope+ the only things that
$an a$$ess it a'ter the $ode blo$% are the s)bro)tines* =ote that a re'eren$e to B$nt is never ta%en+
ho-ever perl %no-s that B$nt is needed by the s)bro)tines and there'ore %eeps it aro)nd* /he in$ and
de$ s)bro)tines are s)bro)tine $los)res*
my GcntH5%
sub incTGcntFF% print .cnt is 7Gcnt78n.%W
sub decTGcnt''% print .cnt is 7Gcnt78n.%W
D cnt is 717
D cnt is 747
D cnt is 77
D cnt is 747
D cnt is 717
D cnt is 747
S)bro)tine names are li%e names o' pa$%age variables* /he s)bro)tine gets pla$ed in the $)rrent
de$lared pa$%age namespa$e* /here'ore+ named s)bro)tines are li%e pa$%age variables in that+ on$e
de$lared+ they never go o)t o' s$ope or get garbage $olle$ted*
#., !ac=age 'aria2les (eisited
Pa$%age variables are not evil+ they are <)st global variables+ and they inherit all the possible problems
asso$iated -ith )sing global variables in yo)r $ode* In the event yo) 1> end )p )sing a pa$%age
variable in yo)r $ode+ they do have some advantages* /hey are global+ -hi$h means they $an be a
$onvenient -ay 'or several di''erent blo$%s o' perl $ode to tal% amongst themselves )sing an agreed
)pon global variable as their $hannel*
Imagine several s)bro)tines a$ross several 'iles that all -ant to $he$% a global variable:
B1evelopment::7erbose* I' this variable is tr)e+ these s)bro)tines print detailed in'ormation* I' it is
'alse+ these s)bro)tines print little or no in'ormation*
pac,age De"e!opment%
our GVerboseH1%
sub (ompi!e T
if NGDe"e!opmentBBVerboseO T
print .compi!ing8n.% W
sub Lin, T
if NGDe"e!opmentBBVerboseOT
print .!in,ing8n.%
sub @un T
if NGDe"e!opmentBBVerboseOT
print .running8n.%
D compi!ing
D !in,ing
D running
/he three s)bro)tines $o)ld be in di''erent 'iles+ in di''erent pa$%age namespa$es+ and they $o)ld all
a$$ess the B1evelopment::7erbose variable and a$t a$$ordingly*
#.. -alling local78 on !ac=age 'aria2les
Ghen -or%ing -ith global variables+ there are times -hen yo) -ant to save the $)rrent val)e o' the
global variable+ set it to a ne- and temporary val)e+ e(e$)te some 'oreign $ode that -ill a$$ess this
global+ and then set the global ba$% to -hat it -as*
Contin)ing the previo)s e(ample+ say -e -ish to $reate a ,)nSilent s)bro)tine that stores
B1evelopment::7erbose in a temp variable+ $alls the original ,)n ro)tine+ and then sets
B1evelopment::7erbose ba$% to its original val)e*
pac,age De"e!opment%
our GVerboseH1%
sub (ompi!e T
if NGDe"e!opmentBBVerboseO T
print .compi!ing8n.%
sub Lin, T
if NGDe"e!opmentBBVerboseOT
print .!in,ing8n.%
sub @un T
if NGDe"e!opmentBBVerboseOT
print .running8n.%
sub @un#i!ent T
my Gtemp H GDe"e!opmentBBVerbose%
D compi!ing
D !in,ing
/his $an also be a$$omplished -ith the Mlo$al!&M ')n$tion* /he lo$al ')n$tion ta%es a pa$%age variable+
saves o'' the original val)e+ allo-s yo) to assign a temp val)e to it* /hat ne- val)e is seen by anyone
a$$essing the variable* nd at the end o' the le(i$al s$ope in -hi$h lo$al!& -as $alled+ the original
val)e 'or the variable is ret)rned* /he ,)nSilent s)bro)tine $o)ld be -ritten li%e this:
sub @un#i!ent T
Perl originally started -ith nothing b)t pa$%age variables* /he MmyM le(i$al variables -ere not
introd)$ed )ntil perl version 4* So to deal -ith all the pa$%age variables+ perl -as given the lo$al!&
')n$tion* Lo$al is also a good -ay to $reate a temporary variable and ma%e s)re yo) donRt step on
someone elseRs variable o' the same name*
& Subroutines
Perl allo-s yo) to de$lare named s)bro)tines and anonymo)s s)bro)tines+ similar to the -ay yo) $an
de$lare named variables and anonymo)s variables*
).1 $u2routine $igil
S)bro)tines )se the ampersand ! X & as their sigil* #)t -hile the sigils 'or s$alars+ arrays+ and hashes
are mandatory+ the sigil 'or s)bro)tines is optional*
).2 6amed $u2routines
#elo- is the named s)bro)tine de$laration synta(:
sub N-C; +L0(^
=:6 $an be any valid perl identi'ier*
#L>CJ is a $ode blo$% en$losed in parenthesis*
/he =:6 o' the s)bro)tine is pla$ed in the $)rrent pa$%age namespa$e+ in the same -ay Mo)rM
variables go into the $)rrent pa$%age namespa$e* So on$e a named s)bro)tine is de$lared+ yo) may
a$$ess it -ith <)st =:6 i' yo) are in the $orre$t pa$%age+ or -ith a ')lly pa$%age ;)ali'ied name i'
yo) are o)tside the pa$%age* nd yo) $an )se the optional ampersand sigil in either $ase*
pac,age Cy-rea%
sub Ping Tprint .ping8n.%W
D ping
D ping
D ping
D ping
>n$e the $)rrent pa$%age de$laration $hanges+ yo) :?S/ )se a ')lly pa$%age ;)ali'ied s)bro)tine
name to $all the s)bro)tine*
pac,age Cy-rea%
sub Ping Tprint .ping8n.%W
pac,age >our-rea%
[Ping% A error, !oo,ing in current pac,age >our-rea
D ping
D ping
D Undefined subroutine [>our-reaBBPing
).3 /nonymous $u2routines
#elo- is the anonymo)s s)bro)tine de$laration synta(:
sub +L0(^
/his -ill ret)rn a $ode re'eren$e+ similar to ho- \] ret)rns an array re'eren$e+ and similar to ho- CD
ret)rns a hash re'eren$e*
sub $hatKisKit T
my NGsca!arOH]K%
my Gstring H refNGsca!arO%
print .ref returned 7Gstring78n.%
my Gtemp H sub Tprint .Ee!!o8n.%W%
D ref returned 7(0D;7
5.4 Data::Dumper and subroutines
/he $ontents o' the $ode blo$% are invisible to anything o)tside the $ode blo$%* "or this reason+ things
li%e 1ata::1)mper $annot loo% inside the $ode blo$% and sho- yo) the a$t)al $ode* Instead
1ata::1)mper does not even try and <)st gives yo) a pla$e holder that ret)rns a d)mmy string*
my Gtemp H sub Tprint .Ee!!o8n.%W%
print Dumper Gtemp%
D GV-@1 H sub T .DUCC>. W%
).) !assing /rguments to@from a $u2routine
ny val)es yo) -ant to pass to a s)bro)tine get p)t in the parenthesis at the s)bro)tine $all* "or normal
s)bro)tines+ all arg)ments go thro)gh the list $onte(t $r)shing ma$hine and get red)$ed to a list o'
s$alars* /he original $ontainers are not %no-n inside the s)bro)tine* /he s)bro)tine -ill not %no- i'
the list o' s$alars it re$eives $ame 'rom s$alars+ arrays+ or hashes* /o avoid some o' the list $onte(t
$r)shing+ a s)bro)tine $an be de$lared -ith a prototype+ -hi$h are dis$)ssed later*
).* /ccessing /rguments inside $u2routines ia AB
Inside the s)bro)tine+ the arg)ments are a$$essed via a spe$ial array $alled AH+ sin$e all the arg)ments
passed in -ere red)$ed to list $onte(t+ these arg)ments 'it ni$ely into an array* /he AH array $an be
pro$essed <)st li%e any other reg)lar array* I' the arg)ments are 'i(ed and %no-n+ the pre'erred -ay to
e(tra$t them is to assign AH to a list o' s$alars -ith meaning')l names*
sub compare T
my NG!eft,GrightOH]K%
return G!eftQHDGright%
/he AH array is Mmagi$alM in that it is really a list o' aliases 'or the original arg)ments passed in*
/here'ore+ assigning a val)e to an element in AH -ill $hange the val)e in the original variable that -as
passed into the s)bro)tine $all* S)bro)tine parameters are e''e$tively I=.>?/*
sub s$ap T N]KO H re"erseN]KO% W
my Gone H .& am one.%
my Gt$o H .& am t$o.%
$arn .one is 7Gone7.%
$arn .t$o is 7Gt$o7.%
D one is 7& am t$o7
D t$o is 7& am one7
ssigning to the entire AH array does not -or%+ yo) have to assign to the individ)al elements* I' s-ap
-ere de'ined li%e this+ the variables Bone and Bt-o -o)ld remain )n$hanged*
sub s$ap T
my NG!eft,GrightOH]K%
]K H NGright,G!eftO% A:@0NG
)., Dereferencing -ode (eferences
1ere'eren$ing a $ode re'eren$e $a)ses the s)bro)tine to be $alled* $ode re'eren$e $an be
dere'eren$ed by pre$eding it -ith an ampersand sigil or by )sing the arro- operator and parenthesis M-
I!&M* /he pre'erred -ay is to )se the arro- operator -ith parens*
my Gtemp H sub Tprint .Ee!!o8n.%W%
Gtemp'DNO% A preferred
D Ee!!o
D Ee!!o
D Ee!!o
).. "mplied /rguments
Ghen $alling a s)bro)tine -ith the MXM sigil pre'i( and no parenthesis+ the $)rrent AH array gets
impli$itly passed to the s)bro)tine being $alled* /his $an $a)se s)btly odd behavior i' yo) are not
e(pe$ting it*
sub secondK!e"e! T
print Dumper 8]K%
sub firstK!e"e! T
A using 7[7 sigi! and no parens.
A doesn7t !oo, !i,e &7m passing any params
A but per! $i!! pass ]K imp!icit!y.
D GV-@1 H U
D 1,
D 4,
D V%
/his generally is not a problem -ith named s)bro)tines be$a)se yo) probably -ill not )se the MXM
sigil* 4o-ever+ -hen )sing $ode re'eren$es+ dere'eren$ing )sing the MXM may $a)se implied arg)ments
to be passed to the ne- s)bro)tine* "or this reason+ the arro- operator is the pre'erred -ay to
dere'eren$e a $ode re'eren$e*
GcodeKref'DNO% A pass nothing, no imp!icit ]K
GcodeKref'DN]KO% A e*p!icit!y pass ]K
GcodeKref'DN 7one7, 7t$o7 O% A pass ne$ parameters
).3 $u2routine (eturn 'alue
S)bro)tines $an ret)rn a single val)e or a list o' val)es* /he ret)rn val)e $an be e(pli$it+ or it $an be
implied to be the last statement o' the s)bro)tine* n e(pli$it ret)rn statement is the pre'erred approa$h
i' any ret)rn val)e is desired*
A return a sing!e sca!ar
sub retKsca! T
return .boo.%
my Gsca!K"ar H retKsca!%
print Dumper 8Gsca!K"ar%
A return a !ist of "a!ues
sub retKarr T
return N1,4,O%
my ]arrK"ar HretKarr%
print Dumper 8]arrK"ar%
D GV-@1 H 87boo7%
D GV-@1 H U
D 1,
D 4,
D V%
).10 (eturning False
/he ret)rn val)e o' a s)bro)tine is o'ten )sed -ithin a boolean test* /he problem is that the s)bro)tine
needs to %no- i' it is $alled in s$alar $onte(t or array $onte(t*
,et)rning a simple M)nde'M val)e !or 0 or 0*0 or MM& -ill -or% in s$alar $onte(t+ b)t in array $onte(t+ it
-ill $reate an array -ith the 'irst element set to )nde'* In boolean $onte(t+ an array -ith one or more
elements is $onsidered tr)e*
ret)rn statement by itsel' -ill ret)rn )nde' in s$alar $onte(t and an empty list in list $onte(t* /his is
the pre'erred -ay to ret)rn 'alse in a s)bro)tine*
sub thisKisKfa!se T
return% A undef or empty !ist
my Gsca!K"ar H thisKisKfa!se%
my ]arrK"ar H thisKisKfa!se%
).11 :sing the caller78 Function in $u2routines
/he $aller!& ')n$tion $an be )sed in a s)bro)tine to 'ind o)t in'ormation abo)t -here the s)bro)tine
-as $alled 'rom and ho- it -as $alled* Caller ta%es one arg)ment that indi$ates ho- 'ar ba$% in the $all
sta$% to get its in'ormation 'rom* "or in'ormation abo)t the $)rrent s)bro)tine+ )se $aller!0&*
sub Eo$:as&(a!!ed T
my ]info H ca!!erN5O%
print Dumper 8]info%
DGV-@1 H U
D 7main7,
D 7./test.p!7,
D 1,
D 7mainBBEo$:as&(a!!ed7,
D 1,
D undef,
D undef,
D undef,
D 4,
D V%
/he $aller!& ')n$tion ret)rns a list o' in'ormation in the 'ollo-ing order
5 Gpac,age pac,age namespace at time of ca!!
1 Gfi!ename fi!ename $here ca!!ed occurred
4 G!ine !ine number in fi!e $here ca!! occurred
Gsubroutine name of subroutine ca!!ed
I Ghasargs true if e*p!icit arguments passed in
J G$antarray !istH1, sca!arH5, "oidHundef
R Ge"a!te*t e"a!uated te*t if an e"a! b!oc,
3 GisKre/uire true if created by .re/uire. or .use.
P Ghints interna! use on!y, disregard
6 Gbitmas, interna! use on!y, disregard
=ote in the e(ample above+ the $ode is in a 'ile $alled test*pl* /he $all o$$)rred in pa$%age main+ the
de'a)lt pa$%age namespa$e+ and it o$$)rred at line 12 o' the 'ile* /he pa$%age ;)ali'ied name o' the
s)bro)tine that -as $alled -as main::4o-GasICalled* /he pa$%age ;)ali'ied name m)st be given
sin$e yo) donRt %no- -hat pa$%age is $)rrent -here the s)bro)tine -as $alled 'rom+ that in'ormation is
hidden in le(i$al s$ope*
).12 The caller78 function and Cwantarray
/he arg)ment o' interest is the B-antarray arg)ment* /his indi$ates -hat ret)rn val)e is e(pe$ted o'
the s)bro)tine 'rom -here it -as $alled* /he s)bro)tine $o)ld have been $alled in void $onte(t
meaning the ret)rn val)e is thro-n a-ay* >r it $o)ld have been $alled and the ret)rn val)e assigned to
a s$alar* >r it $o)ld have been $alled and the ret)rn val)e assigned to a list o' s$alars*
sub (hec,Cy:ant-rray T
my ]info H ca!!erN5O%
my G$antarray H GinfoUJV%
G$antarrayH7undef7 un!essNdefinedNG$antarrayOO%
print .$antarray is 7G$antarray78n.%
(hec,Cy:ant-rray% Aundef
my Gsca! H (hec,Cy:ant-rray% A 5
my ]arr H (hec,Cy:ant-rray% A 1
D $antarray is 7undef7
D $antarray is 757
D $antarray is 717
).13 -onte9t $ensitie $u2routines with wantarray78
3o) $an )se the -antarray variable 'rom $aller!& to $reate a s)bro)tine that is sensitive to the $onte(t in
-hi$h it -as $alled*
sub -rrayProcessor T
my ]info H ca!!erN5O%
my G$antarray H GinfoUJV%
return un!essNdefinedNG$antarrayOO%
ifNG$antarrayO T
return ]K%
W e!se T
return sca!arN]KO%
my ]arrH/$Na!pha bra"o char!ieO%
my Gsca! H -rrayProcessorN]arrO% A
my ]retKarr H -rrayProcessorN]arrO% A a!pha ...
print .sca! is 7Gsca!78n.%
print Dumper 8]retKarr%
D sca! is 77
DGV-@1 H U
D 7a!pha7,
D 7bra"o7,
D 7char!ie7
D V%
+ Compiling and Interpreting
Ghen perl -or%s on yo)r so)r$e $ode+ it -ill al-ays be in one o' t-o modes: $ompiling or interpreting*
Perl has some hoo%s to allo- a$$ess into these di''erent $y$les* /hey are $ode blo$%s that are pre'i(ed
-ith #6GI=+ C46CJ+ I=I/+ and 6=1*
Compiling: translating the so)r$e te(t into ma$hine )sable internal 'ormat*
Interpreting: e(e$)ting the ma$hine )sable+ internal 'ormat*
/he #6GI= blo$% is immediate*
#6GI= -I e(e$)te blo$% as soon as it is $ompiled+ even be'ore $ompiling anything else*
/he other blo$%s+ in$l)ding normal $ode+ do not e(e$)te )ntil a'ter the entire program has been
$ompiled* Ghen anything other than a #6GI= blo$% is en$o)ntered+ they are $ompiled and s$hed)led
'or e(e$)tion+ b)t perl $ontin)es $ompiling the rest o' the program* /he e(e$)tion order is C46CJ+
I=I/+ normal $ode+ and 6=1 blo$%s*
C46CJ -I S$hed)le these blo$%s 'or e(e$)tion a'ter all so)r$e $ode has been $ompiled*
I=I/-I S$hed)le these blo$%s 'or e(e$)tion a'ter the C46CJ blo$%s have e(e$)ted*
normal $ode -I S$hed)le normal $ode to e(e$)te a'ter all I=I/ blo$%s*
6=1 -I S$hed)le 'or e(e$)tion a'ter normal $ode has $ompleted*
:)ltiple #6GI= blo$%s are e(e$)ted immediately in =>,:L de$laration order*
:)ltiple C46CJ blo$%s are s$hed)led to e(e$)te in ,676,S6 de$laration order*
:)ltiple I=I/ blo$%s are s$hed)led to e(e$)te in =>,:L de$laration order*
:)ltiple 6=1 blo$%s are s$hed)led to e(e$)te in ,676,S6 de$laration order*
n e(ample $ontaining several C46CJ+ I=I/+ normal $ode+ and 6=1 blo$%s* /he o)tp)t sho-s the
e(e$)tion order:
;ND T print .;ND 18n. W
(E;(^ T print .(E;(^ 18n. W
+;G&N T print .+;G&N 18n. W
&N&) T print .&N&) 18n. W
print .norma!8n.%
&N&) T print .&N&) 48n. W
+;G&N T print .+;G&N 48n. W
(E;(^ T print .(E;(^ 48n. W
;ND T print .;ND 48n. W
D +;G&N 1
D +;G&N 4
D (E;(^ 4
D (E;(^ 1
D &N&) 1
D &N&) 4
D norma!
D ;ND 4
D ;ND 1
- Code ,euse3 Perl =odules
Lets say yo) $ome )p -ith some really great $h)n%s o' perl $ode that yo) -ant to )se in several
di''erent programs* Perhaps yo) have some s)bro)tines that are espe$ially handy+ and perhaps they
have some private data asso$iated -ith them* /he best pla$e to p)t $ode to be )sed in many di''erent
programs is in a MPerl :od)leM+ and then M)seM that mod)le* perl mod)le is really <)st a 'ile -ith an
invented name and a M*pmM e(tension* /he MpmM is short 'or Mperl mod)leM* I' yo) had some handy
$ode 'or modeling a dog+ yo) might p)t it in a mod)le $alled 1og*pm+ and then yo) -o)ld )se the
M)seM statement to read in the mod)le*
/he $ontent o' a perl mod)le is any valid perl $ode* Generally+ perl mod)les $ontain de$larations+ s)$h
as s)bro)tine de$larations and possibly de$larations o' private or p)bli$ variables* /hese de$lared
s)bro)tines $an be $alled and p)bli$ variables $an be a$$essed by any perl s$ript that )ses the mod)le*
It is standard $onvention that all perl mod)les start o)t -ith a Mpa$%ageM de$laration that de$lares the
pa$%age namespa$e to be the same as the mod)le name* 'ter any ne- pa$%age de$laration yo) -ill
need to t)rn on -arnings+ et$*
4ere is an e(ample o' o)r 1og mod)le*
AAAfi!enameB Dog.pm
pac,age Dog%
use $arnings% use strict% use DataBBDumper%
sub #pea, T print .:oof=8n.% W
1% A CU#) +; L-#) #)-);C;N) &N F&L;
ll perl mod)les m)st end -ith M1FM other-ise yo) -ill get a $ompile error:
Dog.pm did not return a true "a!ue ...
. The use Statement
/he M)seM statement allo-s a perl s$ript to bring in a perl mod)le and )se -hatever de$larations have
been made available by the mod)le* Contin)ing o)r e(ample+ a 'ile $alled s$ript*pl $o)ld bring in the
1og mod)le li%e this:
use Dog%
D :oof=
#oth 'iles+ 1og*pm and s$ript*pl+ -o)ld have to be in the same dire$tory*
/he 1og mod)le de$lares its pa$%age namespa$e to be 1og* /he mod)le then de$lares a s)bro)tine
$alled MSpea%M+ -hi$h+ li%e any normal s)bro)tine+ ends )p in the $)rrent pa$%age namespa$e+ 1og*
>n$e the 1og mod)le has been )sed+ anyone $an $all the s)bro)tine by $alling 1og::Spea%F
5 The use Statement3 )ormall1
/he M)seM statement $an be 'ormally de'ined as this:
use C0DUL;N-C; N L&#)0F-@G# O%
/he M)seM statement is e(a$tly e;)ivalent to this:
re/uire C0DUL;N-C;%
C0DUL;N-C;'DimportN L&#)0F-@G# O%
/he :>1?L6=:6 'ollo-s the pa$%age namespa$e $onvention+ meaning it -o)ld be either a single
identi'ier or m)ltiple identi'iers separated by do)ble-$olons* /hese are all valid :>1?L6=:6S:
use Dog%
use PetsBBDog%
use PetsBBDogBBGerman#hepard%
use PetsBB(atBBPersian%
?ser $reated mod)le names sho)ld be mi(ed $ase* :od)le names -ith all lo-er $ase are reserved 'or
b)ilt in pragmas+ s)$h as M)se -arningsFM :od)le names -ith all )pper $ase letters are <)st )gly and
$o)ld get $on')sed -ith b)ilt in -ords*
/he Mre;)ireM statement is -hat a$t)ally reads in the mod)le 'ile*
Ghen per'orming the sear$h 'or the mod)le 'ile+ Mre;)ireM -ill translate the do)ble $olons into
-hatever dire$tory separator is )sed on yo)r system* "or Lin)( style systems+ it -o)ld be a M.M* So perl
-o)ld loo% 'or Pets::1og::GermanShepard in Pets.1og. 'or a 'ile $alled GermanShepard*pm
3.1 The A"6- /rray
/he Mre;)ireM statement -ill loo% 'or the mod)le path.'ile in all the dire$tories listed in a global array
$alled AI=C* Perl -ill initiali@e this array to some de'a)lt dire$tories to loo% 'or any mod)les* I' yo)
-ant to $reate a s)bdire$tory <)st 'or yo)r mod)les+ yo) $an add this s)bdire$tory to AI=C and perl
-ill 'ind any mod)les lo$ated there*
#e$a)se the Mre;)ireM statement is in a #6GI= blo$%+ tho)gh+ it -ill e(e$)te immediately a'ter being
$ompiled* So this -ill not -or%:
use Dogs%
/his is be$a)se the Mp)shM statement -ill get $ompiled and then be s$hed)led 'or e(e$)tion a'ter the
entire program has been $ompiled* /he M)seM statement -ill get $ompiled and e(e$)ted immediately+
be'ore the Mp)shM is e(e$)ted+ so AI=C -ill not be $hanged -hen M)seM is $alled*
3o) $o)ld say something li%e this:
+;G&N T pushN]&N(,7/home/username/per!modu!es7O% W
use Dogs%
3.2 The use li2 $tatement
/he M)se libM statement is my pre'erred -ay o' adding dire$tory paths to the AI=C array+ be$a)se it
does not need a #6GI= blo$%* Q)st say something li%e this:
use !ib 7/home/username/per!modu!es7%
lso+ 'or yo) Lin)( heads+ note that the home dire$tory symbol MUM is only meaning')l in a lin)( shell*
Perl does not )nderstand it* So i' yo) -ant to in$l)de a dire$tory )nder yo)r home dire$tory+ yo) -ill
need to $all MglobM to translate MUM to something perl -ill )nderstand* /he MglobM ')n$tion )ses the shell
translations on a path*
use !ib g!obN7Y/per!modu!es7O%
use Dogs%
3.3 The !&(0)0"B and !&(00"B &nironment 'aria2les
/he Mre;)ireM statement also sear$hes 'or :>1?L6=:6 in any dire$tories listed in the environment
variable $alled P6,L8LI#* /he P6,L8LI# variable is a $olon separated list o' dire$tory paths* Cons)lt
yo)r shell do$)mentation to determine ho- to set this environment variable*
I' yo) donRt have P6,L8LI# set+ perl -ill sear$h 'or :>1?L6=:6 in any dire$tory listed in the
P6,LLI# environment variable*
3.# The re1uire $tatement
>n$e the re;)ire statement has 'o)nd the mod)le+ perl $ompiles it* #e$a)se the re;)ire statement is in a
#6GI= blo$%+ the mod)le gets e(e$)ted immediately as -ell* /his means any e(e$)table $ode gets
e(e$)ted* ny $ode that is not a de$laration -ill e(e$)te at this point*
/he :>1?L6=:6-Iimport statement is then e(e$)ted*
3.) +;D:0&6/+& 5D import 70"$T;F/(?$8
/he :>1?L6=:6-Iimport!LIS/>",GS& statement is a Mmethod $allM+ -hi$h has not been
introd)$ed yet* method $all is a 'an$y -ay o' doing a s)bro)tine $all -ith a $o)ple o' e(tra bells and
-histles bolted on*
#asi$ally+ i' yo)r perl mod)le de$lares a s)bro)tine $alled MimportM then it -ill get e(e$)ted at this
:ore advan$edly+ one o' the bells and -histles o' a method $all is a thing $alled Minheritan$eM+ -hi$h
has not been introd)$ed yet* So+ to be more a$$)rate+ i' yo)r perl mod)le >, I/S #S6 CLSS!6S&
de$lares a s)bro)tine $alled MimportM then it -ill get e(e$)ted at this time*
/he import method is a -ay 'or a mod)le to import s)bro)tines or variables to the $allerRs pa$%age*
/his happens -hen yo) )se 1ata::1)mper in yo)r s$ript* Ghi$h is -hy yo) $an say
use Data::Dumper;
print Dumper 8]"ar%
instead o' having to say:
use Data::Dumper;
print DataBBDumperBBDumper 8]"ar%
s)bro)tine $alled M1)mperM 'rom the pa$%age 1ata::1)mper gets imported into yo)r pa$%age
3.* The use &9ecution Timeline
/he 'ollo-ing e(ample sho-s the $omplete e(e$)tion timeline d)ring a )se statement*
A=/usr/!oca!/en" per!
use $arnings% use strict% use DataBBDumper%
$arn .<ust before use Dog.%
use Dog N7German#hepard7O%
$arn .<ust after use Dog.%
pac,age Dog%
use $arnings% use strict% use DataBBDumper%
$arn .e*ecuting norma! code.%
sub #pea, T print .:oof=8n.% W
sub import T
$arn .ca!!ing import.%
print .$ith the fo!!o$ing args8n.%
print Dumper 8]K%
1% ACU#) +; L-#) #)-);C;N) &N F&L;
D e*ecuting norma! code at Dog.pm !ine I.
D ca!!ing import at Dog.pm !ine 3.
D $ith the fo!!o$ing args
D GV-@1 H U
D 7Dog7,
D 7German#hepard7
D V%
D <ust before use Dog at ./script.p! !ine I.
D <ust after use Dog at ./script.p! !ine R.
D :oof=
16 bless/2
/he bless!& ')n$tion is so simple that people )s)ally have a hard time )nderstanding it be$a)se they
ma%e it 'ar more $ompli$ated than it really is* ll bless does is $hange the string that -o)ld be ret)rned
-hen re'!& is $alled* /he bless!& ')n$tion is the basis 'or >b<e$t >riented Perl+ b)t bless!& by itsel' is
over-helmingly simple*
K)i$% re'eren$e re'resher: Given an array re'erent+ Aarr+ and a re'eren$e+ BrarrVLAarr+ then $alling
re'!Brarr& -ill ret)rn the string M,,3M*
my ]arrHN1,4,O% A referent
my Grarr H 8]arr% A reference to referent
my Gstr H refNGrarrO% A ca!! refNO
$arn .str is 7Gstr7.%
D str is 7-@@->7
=ormally+ re'!& -ill ret)rn SCL,+ ,,3+ 4S4+ C>16+ or empty-string depending on -hat
type o' re'erent it is re'erred to*
$arn refN8IO%
$arn refNUVO%
$arn refNTWO%
$arn refNsubTWO%
$arn .7..refNIO..7.%
D #(-L-@ at ./script.p! !ine I.
D -@@-> at ./script.p! !ine J.
D E-#E at ./script.p! !ine R.
D (0D; at ./script.p! !ine 3.
D 77 at ./script.p! !ine P.
/he bless ')n$tion ta%es a re'eren$e and a string as inp)t*
/he bless ')n$tion modi'ies the re'erent pointed to by the re'eren$e and atta$hes the given string s)$h
that re'!& -ill ret)rn that string*
/he bless ')n$tion -ill then ret)rn the original re'eren$e*
b!ess @;F;@;N(;, #)@&NG%
4ere is an e(ample o' bless!& in a$tion* =ote this is e(a$tly the same as the $ode in the 'irst e(ample+
b)t -ith one line added to do the bless:
my ]arrHN1,4,O% A referent
my Grarr H 8]arr% A reference to referent
b!essNGrarr, .(ounter.O%
my Gstr H refNGrarrO% A ca!! refNO
$arn .str is 7Gstr7.%
D str is 7(ounter7
Sin$e bless!& ret)rns the re'eren$e+ -e $an $all re'!& on the ret)rn val)e and a$$omplish it in one line:
my GscaHI%
$arn refNb!essN8Gsca,.Four.OO%
$arn refNb!essNUV,.+o*.OO%
$arn refNb!essNTW,.(ur!ies.OO%
$arn refNb!essNsubTW,.-ction.OO%
D Four at ./script.p! !ine J.
D +o* at ./script.p! !ine R.
D (ur!ies at ./script.p! !ine 3.
D -ction at ./script.p! !ine P.
ll bless!& does is a''e$t the val)e ret)rned by re'!&* /hat is it*
3o) might be -ondering -hy the -ord MblessM -as $hosen* I' a religio)s 'ig)re too% -ater and blessed
it+ then people -o)ld re'er to it as Mholy -aterM* /he $onstit)tion and ma%e)p o' the -ater did not
$hange+ ho-ever it -as given a ne- name+ and be$a)se o' that name it might be )sed di''erently*
In perl+ bless!& $hanges the name o' a re'erent* It does not a''e$t the $ontents o' the re'erent+ only the
name ret)rned by re'!&* #)t be$a)se o' this ne- name+ the re'erent might be )sed di''erently or behave
di''erently* Ge -ill see this di''eren$e -ith method $alls*
11 =ethod Calls
Ge have seen method $alls be'ore* /he MODULENAME->import(LISTOFARGS) -as a method
$all+ b)t -e had to do some hand-aving to get beyond it+ $alling it a 'an$y s)bro)tine $all*
K)i$% revie- o' pa$%age ;)ali'ied s)bro)tine names: Ghen yo) de$lare a s)bro)tine+ it goes into the
$)rrent pa$%age namespa$e* 3o) $an $all the s)bro)tine )sing its short name i' yo) are still in the
pa$%age* >r yo) $an )se the ')lly ;)ali'ied pa$%age name+ and be g)aranteed it -ill -or% every time*
pac,age Dog%
sub #pea, T print .:oof8n.% W
D :oof
D :oof
method $all is similar* 4ere is the generi$ de'inition:
&NV0(-N) 'D C;)E0D N L&#)0F-@G# O%
/he I=7>C=/ is the thing that Minvo%edM the :6/4>1* n invo$ant $an be several di''erent
things+ b)t the simplest thing it $an be is <)st a bare-ord pa$%age name to go loo% 'or the s)bro)tine
$alled :6/4>1*
Dog 'D #pea,%
D :oof
So it is almost the same as )sing a pa$%age ;)ali'ied s)bro)tine name 1og::Spea%* So -hat is
"irst+ the I=7>C=/ al-ays gets )nshi'ted into the AH array in the s)bro)tine $all*
pac,age Dog%
use warnings; use strict; use Data::Dumper;
sub #pea, T
print Dumper 8]K%
Dog 'D #pea, NO%
D GV-@1 H U
D 7Dog7, A &NV0(-N)
D A first user argument
D V%
/his may not seem very )se')l+ b)t an I=7>C=/ $an be many di''erent things+ some more )se')l
than others* /he se$ond di''eren$e bet-een a s)bro)tine $all and a method $all is inheritan$e*
11.1 "nheritance
Say yo) -ant to model several spe$i'i$ breeds o' dogs* /he spe$i'i$ breeds o' dogs -ill li%ely be able
to inherit some behaviors !s)bro)tine.methods& 'rom a base $lass that des$ribes all dogs* Say -e model
a German Shepard that has the ability to tra$% a s$ent better than other breeds* #)t German Shepards
still bar% li%e all dogs*
pac,age Dog%
use $arnings% use strict% use DataBBDumper%
sub #pea, T
my NGin"ocant, GcountO H ]K%
$arn .in"ocant is 7Gin"ocant7.%
forN1 .. GcountO T $arn .:oof.% W
pac,age #hepard%
use base Dog%
sub )rac, T $arn .sniff, sniff.% W
A=/usr/!oca!/en" per!
use #hepard%
D in"ocant is 7#hepard7 at Dog.pm !ine R.
D :oof at Dog.pm !ine P.
D :oof at Dog.pm !ine P.
D sniff, sniff at #hepard.pm !ine I.
=oti$e that s$ript*pl )sed Shepard+ not 1og* nd s$ript*pl al-ays )sed Shepard as the invo$ant 'or its
method $alls* Ghen s$ript*pl $alled Shepard-ISpea%+ perl 'irst loo%ed in the Shepard namespa$e 'or a
s)bro)tine $alled Shepard::Spea%* It did not 'ind one* So then it loo%ed and 'o)nd a #S6 o' Shepard
$alled 1og* It then loo%ed 'or a s)bro)tine $alled 1og::Spea%+ 'o)nd one+ and $alled that s)bro)tine*
lso noti$e that the s)bro)tine 1og::Spea% re$eived an invo$ant o' MShepardM* 6ven tho)gh perl ended
)p $alling 1og::Spea%+ perl still passes 1og::Spea% the original invo$ant+ -hi$h -as MShepardM in this
Shepard I=46,I/61 the Spea% s)bro)tine 'rom the 1og pa$%age* /he )ne(plained bit o' magi$ is
that inheritan$e )ses the M)se baseM statement to determine -hat pa$%ages to inherit 'rom*
11.2 use 2ase
/his statement:
use base C0DUL;N-C;%
is ')n$tionally identi$al to this:
re/uire C0DUL;N-C;%
pushN]&#-, C0DUL;N-C;O%
/he re;)ire statement goes and loo%s 'or :>1?L6=:6*pm )sing the sear$h pattern that -e
des$ribed in the M)seM se$tion earlier*
/he p)sh!AIS+:>1?L6=:6& is ne-* Ghen a method $all loo%s in a pa$%age namespa$e 'or a
s)bro)tine and does not 'ind one+ it -ill then go thro)gh the $ontents o' the AIS array* /he AIS
array $ontains any pa$%ages that are #S6 pa$%ages o' the $)rrent pa$%age*
/he AIS array is named that -ay be$a)se MShepardM IS M1ogM+ there'ore IS* /he sear$h order is
depth-'irst+ le't-to-right* /his is not ne$essarily the MbestM -ay to sear$h+ b)t it is ho- perl sear$hes+ so
yo) -ill -ant to learn it* I' this approa$h does not -or% 'or yo)r appli$ation+ yo) $an $hange it -ith a
mod)le 'rom CP=*
Imagine a Child mod)le has the 'ollo-ing 'amily inheritan$e tree:
(hi!d.pm HD ]&#- H /$ N Father Cother O%
Father.pm HD ]&#- H /$ N FathersFather FathersCother O%
Cother.pm HD ]&#- H /$ N CothersFather CothersCother O%
FathersFather.pm HD ]&#- H NO%
FathersCother.pm HD ]&#- H NO%
CothersFather.pm HD ]&#- H NO%
CothersCother.pm HD ]&#- H NO%
Perl -ill sear$h 'or Child-I:ethod thro)gh the inheritan$e tree in the 'ollo-ing order:
11.3 "6';-/6T5Disa7B/$&!/-E/?&8
/he MisaM method -ill tell yo) i' #S6PCJG6 e(ists any-here in the AIS inheritan$e tree*
(hi!d'DisaN.CothersCother.O% A )@U;
(hi!d'DisaN.#hepard.O% A F-L#;
11.# "6';-/6T5Dcan7+&TH;D6/+&8
/he M$anM method -ill tell yo) i' the I=7>C=/ $an $all :6/4>1=:6 s)$$ess')lly*
#hepard'DcanN.#pea,.O% A )@U; N:oofO
(hi!d'DcanN.)rac,.O% A F-L#; Ncan7t trac, a scentO
11.) "nteresting "nocants
So 'ar -e have only )sed bare-ord invo$ants that $orrespond to pa$%age names*
Perl allo-s a more interesting invo$ant to be )sed -ith method $alls: a blessed re'erent* ,emember
bless!& $hanges the string ret)rned by re'!&* Gell+ -hen )sing a re'eren$e as an invo$ant+ perl -ill $all
re'!& on the re'eren$e and )se the string ret)rned as starting pa$%age namespa$e to begin sear$hing 'or
the method.s)bro)tine*
4ere is o)r simple 1og e(ample b)t -ith a blessed invo$ant*
pac,age Dog%
use $arnings% use strict% use DataBBDumper%
sub #pea, T
my NGin"ocant, GcountO H ]K%
$arn .in"ocant is 7Gin"ocant7.%
forN1 .. GcountO T $arn .:oof.% W
W 1%
A=/usr/!oca!/en" per!
use Dog%
my Gin"ocantHb!ess TW,7Dog7% AAA +L;##;D &NV0(-N)
D in"ocant is 7DogHE-#EN5*P14I6IO7 at Dog.pm !ine R
D :oof at Dog.pm !ine P.
D :oof at Dog.pm !ine P.
/he my $invocant=bless {},"Dog"; is the ne- line* /he bless part $reates an anonymo)s
hash+ CD+ and blesses it -ith the name M1ogM* I' yo) $alled re'!Binvo$ant&+ it -o)ld ret)rn the string
So perl )ses M1ogM as its M$hildM $lass to begin its method sear$h thro)gh the hierar$hy tree* Ghen it
'inds the method+ it passes the original invo$ant+ the anonmo)s hash+ to the method as the 'irst
Gell+ sin$e -e have an anonymo)s hash passed aro)nd any-ay+ maybe -e $o)ld )se it to store some
in'ormation abo)t the di''erent dogs that -e are dealing -ith* In 'a$t+ -e already %no- all the grammar
-e need to %no- abo)t >b<e$t >riented Perl Programming+ -e <)st need to spea% di''erent senten$es
12 Procedural Perl
So 'ar+ all the perl $oding -e have done has been Mpro$ed)ralM perl* Ghen yo) hear Mpro$ed)ralM thin%
o' MPi$ardM+ as in Captain Pi$ard o' the starship 6nterprise* Pi$ard al-ays gave the shipRs $omp)ter
$ommands in the 'orm o' pro$ed)ral statements*
(omputer, set $arp dri"e to J.
(omputer, set shie!ds to .off..
(omputer, fire $eaponsB phasers and photon
/he s)b<e$t o' the senten$es -as al-ays MComp)terM* In pro$ed)ral programming+ the s)b<e$t
M$omp)terM is implied+ the -ay the s)b<e$t Myo)M is implied in the senten$e: MStopPM
/he verb and dire$t ob<e$t o' Pi$ardRs senten$es be$ome the s)bro)tine name in pro$eed)ral
programming* Ghatever is le't be$ome arg)ments passed in to the s)bro)tine $all*
fireK$eapons /$Nphasers photonKtorpedoesO%
13 !b>ect !riented Perl
>b<e$t oriented perl does not )se an implied MComp)terM as the s)b<e$t 'or its senten$es* Instead+ it )ses
-hat -as the dire$t ob<e$t in the pro$ed)ral senten$es and ma%es it the s)b<e$t in ob<e$t oriented
:arp Dri"e, set yourse!f to J.
#hie!ds, set yourse!f to .off..
Phasors, fire yourse!f.
)orpedoes, fire yourse!f.
#)t ho- -o)ld -e $ode these senten$esZ
4ere is a minimal e(ample o' ob<e$t oriented perl* /here is a $lass $alled ^nimalS* It has a $onstr)$tor
$alled :a%e=e- and a method $alled Spea%* /he s$ript )ses the nimal mod)le+ $reates instan$es o'
nimal ob<e$ts+ and $alls the Spea% method on ea$h one*
pac,age -nima!%
sub Ca,eNe$ T A our constructor
my NGin"ocant,GnameOH]K% A c!ass and name are passed in
my Gob<ect H TW% A hash to store data
Gob<ect'DTNameWHGname% A put name into hash
b!essNGob<ect, Gin"ocantO% A b!ess hash into c!ass
return Gob<ect% A return hash/instance/ob<ect
sub #pea, T A some method
my NGob<OH]K% A hash/instance/ob<ect passed in
my Gname H Gob<'DTNameW% A get name of this instance
print .Gname gro$!s8n.% A say $ho is spea,ing
A=/usr/!oca!/en" per!
use -nima!%
A note that 7-nima!7 is passed in to Ca,eNe$
A as first parameter. 7#amson7 is second parameter.
A 7-nima!7 becomes Gin"ocant. 7#amson7 becomes Gname.
my G!ion H -nima!'DCa,eNe$N7#amson7O% A create an instance
A note that the b!essed hash reference, G!ion, is passed
A into #pea, method as first parameter. &t becomes Gob<.
G!ion'D#pea,NO% A ca!! method on this instance
my Gtiger H -nima!'DCa,eNe$N7FuMMba!!7O%
my Gbear H -nima!'DCa,eNe$N7#mo,ey7O%
D #amson gro$!s
D FuMMba!! gro$!s
D #mo,ey gro$!s
So -hatZ #asi$ >b<e$t >riented does nothing that $annot be <)st as easily done in pro$ed)ral perl* #)t
on$e yo) start adding things li%e inheritan$e and polymorphism+ the advantages o' ob<e$t oriented
be$ome more obvio)s* /he 'irst thing -e -ant to do is pro$ess ob<e$ts as an array+ rather than as
individ)ally named variables*
Lets ret)rn to a 'amiliar e(ample+ o)r 1og mod)le* ss)me -e -ant to %eep tra$% o' several dogs at
on$e* Perhaps -e are $oding )p an inventory system 'or a pet store*
"irst+ -e -ant a $ommon -ay to handle all pets+ so -e $reate an nimal*pm perl mod)le* /his mod)le
$ontains one s)bro)tine that ta%es the invo$ant and a =ame+ p)ts the =ame into a hash+ blesses the
hash+ and ret)rns a re'eren$e to the hash* /his ret)rn val)e be$omes a MnimalM ob<e$t* /his s)bro)tine
is an ob<e$t $ontr)$tor*
/hen -e $reate a 1og mod)le that )ses nimal as its base to get the $ontr)$tor* Ge then add a method
to let dogs bar%* /he method prints the name o' the dog -hen they bar% so -e %no- -ho said -hat*
/he s$ript*pl $reates three dogs and stores them in an array* /he s$ript then goes thro)gh the array and
$alls the Spea% method on ea$h ob<e$t*
pac,age -nima!%
sub Ne$ T
my NGin"ocant,GnameOH]K%
return b!essNTNameHDGnameW,Gin"ocantO%
W 1%
pac,age Dog%
use base -nima!%
sub #pea, T
my NGob<OH]K%
my GnameHGob<'DTNameW%
$arn .Gname says :oof.%
W 1%
A=/usr/!oca!/en" per!
use Dog%
my ]pets%
A create Dog ob<ects and put them in ]pets array
foreach my Gname /$N+utch #pi,e F!uffyO T
pushN]pets, Dog'DNe$NGnameOO%
A ha"e e"ery pet spea, for themse!"es.
foreach my Gpet N]petsO T Gpet'D#pea,% W
D +utch says :oof at Dog.pm !ine 3.
D #pi,e says :oof at Dog.pm !ine 3.
D F!uffy says :oof at Dog.pm !ine 3.
=oti$e the last 'orea$h loop in s$ript*pl says Bpet-ISpea%* /his is ob<e$t oriented programming+
be$a)se i' yo) translated that statement to 6nglish+ it -o)ld be MPet+ spea% 'or yo)rsel'M* /he s)b<e$t o'
the senten$e is MPetM+ rather than the implied MComp)terM o' pro$ed)ral programming*
>b<e$t >riented Programming statements are o' the 'orm:
Gsub<ect 'D "erb N ad<ecti"es, ad"erbs, etc O%
13.1 -lass
/he term M$lassM re'ers to a perl pa$%age.mod)le that is )sed in an ob<e$t oriented -ay* perl pa$%age
that is designed 'or pro$ed)ral )se is simply $alled a pa$%age* I' itRs an >> pa$%age+ yo) $an $all it a
13.2 !olymorphism
Polymorphism is a real 'an$y -ay o' saying having di''erent types o' ob<e$ts that have the same
methods* 6(panding o)r previo)s e(ample+ -e might -ant to add a Cat $lass to handle $ats at the pet
pac,age (at%
use base -nima!%
sub #pea, T
my Gob<Hshift%
my GnameHGob<'DTNameW%
$arn .Gname says Ceo$.%
W 1%
/hen -e modi'y s$ript*pl to p)t some $ats in the Apets array*
A=/usr/!oca!/en" per!
use Dog% use (at%
my ]pets%
Acreate some dog ob<ects
foreach my Gname /$N+utch #pi,e F!uffyO T
pushN]pets, Dog'DNe$NGnameOO%
A create some cat ob<ects
foreach my Gname /$NFang Furba!! F!uffyO T
pushN]pets, (at'DNe$NGnameOO%
A ha"e a!! the pets say something.
foreach my Gpet N]petsO T
Gpet'D#pea,% A po!ymorphism at $or,
D +utch says :oof at Dog.pm !ine 3.
D #pi,e says :oof at Dog.pm !ine 3.
D F!uffy says :oof at Dog.pm !ine 3.
D Fang says Ceo$ at (at.pm !ine 3.
D Furba!! says Ceo$ at (at.pm !ine 3.
D F!uffy says Ceo$ at (at.pm !ine 3.
=oti$e ho- the last loop goes thro)gh all the pets and has ea$h one spea% 'or themselves* Ghether its a
dog or $at+ the animal -ill say -hatever is appropriate 'or its type* /his is polymorphism* /he $ode
pro$esses a b)n$h o' ob<e$ts and $alls the same method on ea$h ob<e$t* nd ea$h ob<e$t <)st %no-s
ho- to do -hat it sho)ld do*
13.3 $:!&(
S?P6,:: is an interesting bit o' magi$ that allo-s a $hild ob<e$t -ith a method $all that same method
name in its parentRs $lass*
#a$% to the dogs* /o shorten the e(ample+ the $onstr)$tor =e- -as moved to 1og*pm* /he Shepard
mod)le )ses 1og as its base+ and has a Spea% method that gro-ls+ and then $alls its an$estorRs 1og
version o' spea%*
pac,age Dog%
sub Ne$ T
return b!essNTNameHDGKU1VW,GKU5VO%
sub #pea, T
my GnameHGKU5V'DTNameW%
$arn .Gname says :oof.%
W 1%
pac,age #hepard%
use base Dog%
sub #pea, T
my GnameHGKU5V'DTNameW%
$arn .Gname says Grrr.%
GKU5V'D#UP;@BB#pea,% AAA #UP;@
W 1%
A=/usr/!oca!/en" per!
use $arnings% use strict% use DataBBDumper%
use #hepard%
my GdogH#hepard'DNe$N.#pi,e.O%
D #pi,e says Grrr at #hepard.pm !ine R.
D #pi,e says :oof at Dog.pm !ine P.
Githo)t the magi$ o' S?P6,+ the only -ay that Shepard $an $all 1ogRs version o' spea% is to )se a
')lly pa$%age ;)ali'ied name 1og::Spea%!&F #)t this s$atters hard$oded names o' the base $lass
thro)gho)t Shepard+ -hi$h -o)ld ma%e $hanging the base $lass a lot o' -or%*
I' ShepardRs version o' Spea% simply said BH\0]-ISpea%+ it -o)ld get into an in'inite loop $alling itsel'
re$)rsively* S?P6, is a -ay o' saying+ Mloo% at my an$estors and $all their version o' this method*M
/here are some limitations -ith S?P6,* Consider the big 'amily tree inheritan$e diagram in the M)se
baseM se$tion o' this do$)ment !the one -ith Child as the root+ "ather and :other as parents+ and
"athers"ather+ "athers:other+ et$ as grandparents&*
Imagine an ob<e$t o' type MChildM* I' M"atherM has a method $alled Spea% and that method $alls
S?P6,::Spea%+ the only mod)les that -ill get loo%ed at is M"athers"atherM and M"athers:otherM*
S?P6, loo%s )p the hierar$hy starting at the $lass 'rom -here it -as $alled* /his means i' the method
"athers"ather needed to $all -as in :others:other+ then S?P6, -ill not -or%*
/his $o)ld be $onsidered a good thing+ sin$e yo) -o)ld ass)me that "ather -as designed only %no-ing
abo)t "athers"ather and "athers:other* Ghen "ather -as $oded+ :others:other -as a $omplete
stranger he -o)ld not meet 'or years to $ome* So designing "ather to rely on his ')t)re+ have-not-even-
met-her-yet mother-in-la-+ $o)ld be $onsidered a bad thing*
4o-ever+ it is legitimate to have -hat yo) might $onsider to be M)niversalM methods that e(ist 'or
every $lass* Instead o' a $lass $alled MChildM imagine a $lass $alled MCo)plebo)t/oGet:arriedM+ and
every base $lass has a method $alled MContrib)te/oGeddingM* In that $ase+ every $lass $o)ld do its
part+ and then $all S?P6,::Contrib)te/oGedding* /he "ather>'/he#ride -o)ld pay 'or the -edding+
the "ather>'/heGroom -o)ld pay 'or the rehersal dinner+ and so on and so 'orth*
?n'ort)nately+ there is no easy+ b)ilt-in -ay to do this in perl*
I -ill re'er yo) to the M=6N/*pmM mod)le available on CP=*
S?P6, does have its )ses+ tho)gh* :any times a $lass might e(ist that does L:>S/ -hat yo) -ant
it to do* ,ather than modi'y the original $ode to do -hat yo) -ant it to+ yo) $o)ld instead $reate a
derived $lass that inherits the base $lass and re-rite the method to do -hat yo) -ant it to do* "or
e(ample+ yo) might -ant a method that $alls its parent method b)t then m)ltiplies the res)lt by min)s
one or something* In $ases li%e this+ S?P6, -ill do the tri$%*
13.# ;24ect Destruction
>b<e$t destr)$tion o$$)rs -hen all the re'eren$es to a spe$i'i$ ob<e$t have gone o)t o' le(i$al s$ope+
and the ob<e$t is s$hed)led 'or garbage $olle$tion* Q)st prior to deleting the ob<e$t and any o' its
internal data+ perl -ill $all the 16S/,>3 method on the ob<e$t* I' no s)$h method e(ists+ perl silently
moves on and $leans )p the ob<e$t data*
pac,age Dog%
sub Ne$ T
return b!essNTNameHDGKU1VW,GKU5VO%
sub D;#)@0> T
$arn NNGKU5V'DTNameWO.. has been so!d.O%
W 1%
A=/usr/!oca!/en" per!
use $arnings% use strict% use DataBBDumper%
use Dog%
my GdogHDog'DNe$N.#pi,e.O%
D #pi,e has been so!d at Dog.pm !ine 3.
/he 16S/,>3 method has similar limitations as S?P6,* Gith an ob<e$t that has a $omple(
hierar$hi$al 'amily tree+ perl -ill only $all the "I,S/ method o' 16S/,>3 that it 'inds in the
an$estry* I' :other and "ather both have a 16S/,>3 method+ then :otherRs not going to handle her
demise properly and yo) -ill li%ely have ghosts -hen yo) r)n yo)r program*
/he =6N/*pm mod)le on CP= also solves this limitation*
1# !b>ect !riented ,eie"
1#.1 +odules
/he basis 'or $ode re)se in perl is a mod)le* perl mod)le is a 'ile that ends in M*pmM and de$lares a
pa$%age namespa$e that !hope')lly& mat$hes the name o' the 'ile* /he mod)le $an be designed 'or
pro$ed)ral programming or ob<e$t oriented programming !>>&* I' the mod)le is >>+ then the mod)le
is sometimes re'erred to as a M$lassM*
1#.2 use +odule
/he $ode in a perl mod)le $an be made available to yo)r s$ript by saying M)se :>1?L6FM /he M)seM
statement -ill loo% 'or the mod)le in the dire$tories listed in the P6,L8LI# environment variable and
then the dire$tories listed in the AI=C variable*
/he best -ay to add dire$tories to the AI=C variable is to say
use !ib ./path/to/dir.%
ny do)ble-$olons !::& in the mod)le name being )sed get $onverted to a dire$tory separator symbol o'
the operating system*
1#.3 2less @ constructors
I' the mod)le is designed 'or pro$ed)ral programming+ it -ill provide s)bro)tine de$larations that $an
be $alled li%e normal s)bro)tines* I' the mod)le is designed 'or ob<e$t oriented )se+ it -ill de$lare
s)bro)tines that -ill be )sed as $onstr)$tors or methods*
Constr)$tors are s)bro)tines that $reate a re'eren$e to some variable+ )se the re'eren$e to bless the
variable into the $lass+ and then ret)rn the re'eren$e* >n$e its re'erent is blessed+ it $an be )sed as an
ob<e$t+ and the re'eren$e is a handy -ay o' passing the ob<e$t aro)nd* /he ob<e$t is )s)ally a hash*
Jeys to the hash $orrespond to ob<e$t attrib)te names+ and the 7al)es $orrespond to the attrib)te val)es
spe$i'i$ to that parti$)lar instan$e* In the nimal*pm mod)le e(ample+ one %ey -as M=ameM+ and
di''erent instan$es had =ame val)es o' M"l)''yM+ MSpi%eM+ and so on*
/he best -ay o' $alling a $onstr)$tor is to )se the arro- operator:
my Gob<ect H (!assname'D(onstructorNargumentsO%
In the nimal*pm $lass+ this -o)ld loo% li%e:
my Gpet H -nima!'DNe$N7#pi,e7O
/he name o' the $onstr)$tor $an be any valid s)bro)tine name+ b)t is )s)ally Mne-M or M=e-M*
1#.# +ethods
>n$e an instan$e o' an ob<e$t has been $onstr)$ted+ methods $an be $alled on the instan$e to get
in'ormation+ $hange val)es+ per'orm operations+ et$* method is simply a s)bro)tine that re$eives a
re'eren$e to the instan$e variable as its 'irst arg)ment* :ethods sho)ld be tho)ght o' as Ma$tionsM to be
per'ormed on the instan$e+ or MverbsM in a senten$es -ith instan$es being the Ms)b<e$tM*
In the above e(amples+ MSpea%M -as a method that )sed the =ame o' the instan$e to print o)t MBname
says -oo'M* /he pre'erred -ay o' $alling a method is )sing the arro- method*
G0b<ect&nstance 'D Cethod N !ist of arguments O%
In the nimal*pm e(ample+ this -o)ld loo% li%e:
1#.) "nheritance
Classes $an inherit methods 'rom base $lasses* /his allo-s many similar $lasses to p)t all their
$ommon methods in a single base $lass* /o have a $lass inherit 'rom a base $lass+ )se the M)se baseM
use base +ase(!assName%
In one e(ample above+ the Cat and 1og $lasses both inherit 'rom a $ommon nimal $lass* #oth 1og
and Cat $lasses inherit the $onstr)$tor M=e-M method 'rom the nimal base $lass*
/he $lasses Cat and 1og inherit 'rom the base $lass nimal* Cat and 1og are MderivedM 'rom nimal*
1#.* ;erriding +ethods and $:!&(
Classes $an override the methods o' their base $lasses* I' a base $lass $ontains a method $alled
M:ethod=ameM+ then a derived $lass $an override the base $lass method by de$laring its o-n
s)bro)tine $alled :ethod=ame*
In the e(amples above+ the GermanShepard derived $lass overrode the 1og base $lass Spea% method
-ith its o-n method*
I' a derived $lass overrides a method o' its base $lass+ it may -ant to $all its base $lass method* /he
only -ay to a$$omplish this is -ith the S?P6,:: pse)dopa$%age name* /he GermanShepard method
named Spea% $alled the 1og version o' Spea% by $alling:
1& CP*N
CP= is an a$ronym 'or MComprehensive Perl r$hive =et-or%M* /here is a CP= -ebsite+ -hi$h
$ontains a plethora o' perl mod)le 'or anyone to do-nload* /here is also a CP= perl mod)le+ -hi$h
provides a shell inter'a$e 'or a)tomating the do-nloading o' perl mod)les 'rom the CP= -ebsite*
Mperldo$M )tility $omes -ith perl that allo-s vie-ing o' P>1+ -hi$h is MPlain >ld 1o$)mentationM
embedded -ithin the perl mod)les do-nloaded 'rom CP=* nd 'inally+ there is a Mh2(sM )tility+
-hi$h a)tomates the $reation o' a mod)le to be )ploaded to CP=*
1).1 -!/6% The >e2 $ite
CP= is a -ebsite that $ontains all things perl: help+ "Ks+ so)r$e $ode to install perl+ and most
importantly+ a plethora o' perl mod)le so that yo) $an re-)se someone elseRs $ode*
CP= $ontains a n)mber o' sear$h engines* >n$e yo) 'ind a mod)le that might do -hat yo) need+ yo)
$an vie- the ,61:6 'ile that is )s)ally available online be'ore a$t)ally do-nloading the mod)le* I'
the ,61:6 loo%s promising+ then do-nload the tarball+ -hi$h -ill be a 'ile -ith a tar*g@ e(tension*
4ere is the standard installation steps 'or a mod)le* /his e(ample is 'or the =6N/*pm mod)le+ -hi$h is
$ontained in =6N/-0*90*tar*g@ !yo) sho)ld )se the latest version+ i' available*&
> gunzip NEXT-0.60.tar.gz
> tar -xf NEXT-0.60.tar
D cd N;?)'5.R5
"rom here+ most mod)les install -ith the e(a$t same $ommands:
D per! Ca,efi!e.PL
D ma,e
D ma,e test
D su root
D ma,e insta!!
D e*it
/he Mma%e installM step re;)ires root privileges* /he Me(itM step is sho-n <)st so yo) remember to log
o)t 'rom root*
I' yo) do not have root privileges and the mod)le is p)re perl !<)st a *pm 'ile&+ then yo) $an $opy the
*pm 'ile to yo)r home dire$tory !or any-here yo) have read.-rite privileges&+ and then set yo)r
P6,L8LI# environment variable to point to that dire$tory*
1).2 -!/6% The !erl +odule
/he CP=*pm mod)le is a mod)le that a)tomates the installation pro$ess* yo) give it the name o' a
mod)le+ and it do-nloads it 'rom the -eb+ )ntars it+ and installs it 'or yo)* :ore interestingly+ it -ill
install any dependen$ies 'or yo) as -ell* I' yo) install a mod)le that re;)ires a separate mod)le+ it
installs both mod)les 'or yo) -ith one $ommand*
CP=*pm -ill -ant yo) to have lyn( installed on yo)r ma$hine* Lyn( is a te(t-based -ebbro-ser*
CP=*pm -ill also -ant n$'tpget+ -hi$h is an Internet 'ile trans'er program 'or s$ripts* Install these
on yo)r system be'ore r)nning the CP= mod)le*
/he CP=*pm mod)le is r)n 'rom a shell mode as root !yo) need root privileges to do the install&*
Change to root+ and then r)n the CP=*pm mod)le shell*
D su root
D per! 'C(P-N 'e she!!
/he 'irst time it is r)n+ it -ill as% yo) a b)n$h o' $on'ig)ration ;)estions* :ost $an be ans-ered -ith
the de'a)lt val)e !press Tret)rnI&*
4ere is a log 'rom the CP= being r)n 'or the 'irst time on my ma$hine:
-re you ready for manua! configurationX UyesV
(P-N bui!d and cache directoryX U/home/greg/.cpanV
(ache siMe for bui!d directory Nin C+OX U15V
Perform cache scanning Natstart or ne"erOX UatstartV
(ache metadata Nyes/noOX UyesV
>our termina! e*pects &#0'PPJ6'1 Nyes/noOX UyesV
Po!icy on bui!ding prere/uisites Nfo!!o$, as, or
ignoreOX Uas,V
:here is your gMip programX U/usr/bin/gMipV
:here is your tar programX U/bin/tarV
:here is your unMip programX U/usr/bin/unMipV
:here is your ma,e programX U/usr/bin/ma,eV
:here is your !yn* programX UV
D /usr/bin/!yn*
:here is your $get programX U/usr/bin/$getV
:here is your ncftpget programX UV
D /usr/bin/ncftpget
:here is your ftp programX U/usr/bin/ftpV
:hat is your fa"orite pager programX U/usr/bin/!essV
:hat is your fa"orite she!!X U/bin/bashV
Parameters for the 7per! Ca,efi!e.PL7 commandX
>our choiceB UV
Parameters for the 7ma,e7 commandX
>our choiceB UV
Parameters for the 7ma,e insta!!7 commandX
>our choiceB UV
)imeout for inacti"ity during Ca,efi!e.PLX U5V
>our ftpKpro*yX
>our httpKpro*yX
>our noKpro*yX
#e!ect your continent Nor se"era! nearby
continentsO UV
#e!ect your country Nor se"era! nearby countriesO UV
#e!ect as many U@Ls as you !i,e,
put them on one !ine, separated by b!an,s UV
D J 3 11 1
;nter another U@L or @;)U@N to /uitB UV
>our fa"orite :-&) ser"erX
/hat last line is a$t)ally the $pan shell prompt* /he ne(t time yo) r)n $pan+ it -ill go dire$tly to the
$pan shell prompt*
/he 'irst thing yo) -ill probably -ant to do is ma%e s)re yo) have the latest and greatest $pan*pm
mod)le -ith all the trimmings* t the $pan shell prompt+ type the 'ollo-ing $ommand:
cpanD insta!! +und!eBB(P-N
cpanD re!oad cpan
3o) sho)ld then be able to install any perl mod)le -ith a single $ommand* I' $pan en$o)nters any
problems+ it -ill not install the mod)le* I' yo) -ish to 'or$e the install+ then )se the M'or$eM $ommand*
cpanD force insta!! ),
>r yo) $an get the tarball 'rom ---*$pan*org and install it man)ally*
1).3 !lain ;ld Documentation 7!;D8 and perldoc
:od)les on CP= are generally do$)mented -ith P>1* P>1 embeds do$)mentation dire$tly into the
perl $ode* 3o) do not need to %no- P>1 to -rite perl $ode* #)t yo) -ill -ant to %no- ho- to read
P>1 'rom all the mod)les yo) do-nload 'rom CP=* Perl $omes -ith a b)iltin )tility $alled Mperldo$M
-hi$h allo-s yo) to loo% )p perl do$)mentation in P>1 'ormat*
D per!doc per!doc
D per!doc N;?)
D per!doc DataBBDumper
1).# -reating +odules for -!/6 with h29s
I' yo) -ish to $reate a mod)le that yo) intend to )pload to CP=+ perl $omes -ith a )tility Mh2(sM
-hi$h+ among other things+ -ill $reate a minimal set o' all the 'iles needed* /his 'irst $ommand -ill
$reate a dire$tory $alled MnimalM and pop)late it -ith all the 'iles yo) need* /he remainder o' the
$ommands sho- yo) -hat steps yo) need to ta%e to $reate a *tar*g@ tarball that $an be )ploaded to
CP= and do-nloaded by others )sing the $pan*pm mod)le*
D h4*s '? 'n -nima! A create the structure
D cd -nima!/!ib A go into modu!e dir
D edit -nima!.pm A edit modu!e
D cd ../t A go into test dir
D edit -nima!.t A edit test
D cd .. A go to ma,e directory
D per! Ca,efi!e.PL A create ma,e fi!e
D ma,e A run ma,e
D ma,e test A run the test in t/
D ma,e dist A create a .tar.gM fi!e
1+ The Next 4eel
3o) no- %no- the ')ndamentals o' pro$ed)ral perl and ob<e$t oriented perl* "rom this point 'or-ard+
any ne- topi$s may in$l)de a dis$)ssion o' a perl b)iltin 'eat)re or something available 'rom CP=*
Some o' perlRs b)iltin 'eat)res are some-hat limited and a CP= mod)le greatly enhan$es and.or
simpli'ies its )sage*
1- Command 4ine *rguments
S$ripts are o'ten $ontrolled by the arg)ments passed into it via the $ommand line -hen the s$ript is
e(e$)ted* rg)ments might be a s-it$h+ s)$h as M-hM to get help*
D myscript.p! 'h
M-vM s-it$h might t)rn verboseness on*
D anotherscript.p! '"
S-it$hes might by 'ollo-ed by an arg)ment asso$iated -ith the s-it$h* M-inM s-it$h might be
'ollo-ed by a 'ilename to be )sed as inp)t*
D thatscript.p! 'in data.t*t
n arg)ment $o)ld indi$ate to stop pro$essing the remaining arg)ments and to pro$ess them at a later
point in the s$ript* /he M--M arg)ment $o)ld be )sed to indi$ate that arg)ments be'ore it are to be )sed
as perl arg)ments and that arg)ments a'ter it are to be passed dire$tly to a $ompiler program that the
s$ript -ill $all*
D mytest.p! 'in testI4.t*t '' FdefineFF-#)
:ore advan$ed arg)ments:
Single $hara$ter s-it$hes $an be l)mped together* Instead o' M-( -y -@M+ yo) $o)ld say M-(y@M*
>ptions $an be stored in a separate 'ile* 'ile might $ontain a n)mber o' options al-ays needed to do a
standard ')n$tion+ and )sing M-' option'ile*t(tM -o)ld be easier than p)tting those options on the
$ommand line ea$h and every time that ')n$tion is needed* /his -o)ld allo- a )ser to )se the option
'ile and then add other options on the $ommand line*
D thisscript.p! 'f optionfi!e.t*t '"
>ptions $an have ')ll and abbreviated versions to a$tivate the same option*
/he option M-verboseM $an also -or% as M-vM* >ptions operate independent o' spa$ing*
'f H options.t*t
1,.1 A/(?'
Perl provides a$$ess to all the $ommand line arg)ments via a global array A,G7* /he te(t on the
$ommand line is bro%en )p any-here -hitespa$e o$$)rs+ e($ept 'or ;)oted strings*
A=/usr/bin/en" per!
use $arnings% use strict% use DataBBDumper%
print Dumper 8]-@GV%
D script.p! '" 'f options.t*t .he!!o $or!d.
D GV-@1 H U
D 7'"7,
D 7'f7,
D 7options.t*t7,
D 7he!!o $or!d7
D V%
I' yo) need to pass in a -ild-$ard s)$h as _*t(t then yo) -ill need to p)t it in ;)otes or yo)r operating
system -ill repla$e it -ith a list o' 'iles that mat$h the -ild$ard pattern*
A=/usr/bin/en" per!
use $arnings% use strict% use DataBBDumper%
print Dumper 8]-@GV%
D ./test.p! L.p!
D GV-@1 H U
D 7script.p!7,
D 7test.p!7
D V%
D ./test.p! .L.p!.
D GV-@1 H U
D 7L.p!7
D V%
Simple pro$essing o' A,G7 -o)ld shi't o'' the bottom arg)ment+ pro$ess it+ and move on to the
ne(t arg)ment* /he 'ollo-ing e(ample -ill handle simple $ommand line arg)ments des$ribed above*
A create a pac,age "ariab!e for each option
our Gfn%
our GdebugH5%
A create subroutines for options that do things
sub printKhe!p T
print .'d for debug8n'f for fi!ename8n.%
A get the first/ne*t argument and process it.
$hi!eNsca!arN]-@GVOO T
my GargHshiftN]-@GVO%
ifNGarg e/ 7'h7O TprintKhe!p%W
e!sifNGarg e/ 7'f7O TGfn H shiftN]-@GVO%W
e!sifNGarg e/ 7'd7O TGdebugH1%W
e!se T die .un,no$n argument 7Garg7.% W
Pa$%age !o)r& variables are )sed instead o' le(i$al !my& variables be$a)se $ommand line arg)ments
sho)ld be $onsidered global and pa$%age variables are a$$essible every-here* I' yo) -rote a s$ript that
)sed M-dM to t)rn on deb)g in'ormation+ yo) -o)ld -ant this to t)rn on deb)gging in any separate
mod)les that yo) -rite+ not <)st yo)r s$ript*pl s$ript*
Pa$%age MmainM is the de'a)lt pa$%age and a good pla$e to p)t $ommand line arg)ment related
variables* >)tside o' pa$%age main+ $ode -o)ld $he$% 'or Bmain::deb)g being tr)e or 'alse*
I' yo) need to handle a 'e- simple $ommand line arg)ments in yo)r s$ript+ then the above e(ample o'
pro$essing A,G7 one at a time is probably s)''i$ient* I' yo) need to s)pport more advan$ed
$ommand line arg)ments+ or a lot o' simple ones+ yo) sho)ld loo% at Getopt::1e$lare*
1,.2 ?etoptFFDeclare
/he Getopt::1e$lare mod)le allo-s 'or an easy -ay to de'ine more $ompli$ated $ommand line
arg)ments* /he above e(ample -ith -h+-'+ and -d options $o)ld be -ritten )sing Getopt::1e$lare li%e
use GetoptBBDec!are%
our GfnH77%
our GdebugH5%
my Gargs H GetoptBBDec!are'Dne$N / N
'in Qfi!enameD Define input fi!e
'd )urn debugging 0n
T die .un,no$n arg 7Gun,no$n78n.% W
print .Debug is 7Gdebug78n.%
print .fn is 7Gfn78n.%
/he te(t passed into Getopt::1e$lare is a m)lti-line ;)oted ;!& string* /his string de'ines the arg)ments
that are a$$eptable* =oti$e that -h is not de'ined in the string* /his is be$a)se Getopt::1e$lare
re$ogni@es -h to print o)t help based on the de$laration*
D script.p! 'h
D 'in Qfi!enameD Define input fi!e
D 'd )urn debugging 0n
/he arg)ment de$laration and the arg)ment des$ription is separated by one or more tabs in the string
passed into Getopt::1e$lare*
/he T)n%no-nI mar%er is )sed to de'ine -hat a$tion to ta%e -ith )n%no-n arg)ments+ arg)ments that
are not de'ined in the de$laration*
/he te(t -ithin the $)rly bra$es CBmain::'nVB'ilenameFD is treated as e(e$)table $ode and evaled i' the
de$lared arg)ment is en$o)ntered on the $ommand line* =ote that -ithin the $)rly bra$es+ the global
variables B'n and Bdeb)g are )sed -ith their ')ll pa$%age name* lso+ not that the starting $)rly bra$e
m)st begin on its o-n line separate 'rom the arg)ment de$laration and des$ription*
Getopt::1e$lare re$ogni@es -v as a version $ommand line arg)ment* I' -v is on the $ommand line+ it
-ill print o)t the version o' the 'ile based on Bmain::76,SI>= !i' it e(ists& and the date the 'ile -as
I' \)ndo$)mented] is $ontained any-here in the $ommand line arg)ment des$ription+ then that
arg)ment -ill not be listed in the help te(t+ b)t -ill still be re$ogni@ed i' pla$ed on the $ommand line
!se$ret arg)ments&
\ditto] 'lag in the des$ription -ill )se the same te(t des$ription as the arg)ment <)st be'ore it+ and
any a$tion asso$iated -ith it*
short and long version o' the same arg)ment $an be listed by pla$ing the optional se$ond hal' in
s;)are bra$%ets: -verb\ose] /his -ill re$ogni@e -verb and -verbose as the same arg)ment*
=ormally+ a de$lared arg)ment -ill only be allo-ed to o$$)r on the $ommand line on$e* I' the
arg)ment $an o$$)r more than on$e+ pla$e \repeatable] in the des$ription* Inside the $)rly bra$es+
$alling 'inish!& -ith a tr)e val)e -ill $a)se the $ommand line arg)ments to stop being pro$essed at that
1-.2.1 <etopt??'eclare Sophisticated @xample
/he e(ample on the ne(t page sho-s Getopt::1e$lare being )sed more to its potential*
1* "ilenames to be handled by the s$ript $an be listed on the $ommand line -itho)t any arg)ment pre'i(
2* 7erbosity $an be t)rned on -ith -verbose* It $an be t)rned o'' -ith -;)iet*
2* n )ndo$)mented -1)mp option t)rns on d)mping*
4* ny options a'ter a do)ble dash !--& are le't in A,G7 'or later pro$essing*
8* dditional arg)ments $an be pla$ed in an e(ternal 'ile and loaded -ith -args 'ilename*
/he 6rror!& s)bro)tine -ill report the name o' the 'ile $ontaining any error -hile pro$essing the
arg)ments* rg)ment 'iles $an re'er to other arg)ment 'iles+ allo-ing nested arg)ment 'iles*
9* ny arg)ments that are not de'ined -ill generate an error*
A ad"anced command !ine argument processing
use GetoptBBDec!are%
our GargKfi!eH7(ommand Line7%
our GV;@#&0NH1.51% A '" $i!! use this
our ]fi!es%
our GdebugH5%
our G"erboseH5%
our GdumpH5%
sub Verbose TifNG"erboseOTprint GKU5V%WW
sub ;rror Tdie.;rrorB ..NGKU5VO.. from 7GargKfi!e78n.%W
my Ggrammar H /N
'args QinputD -rg fi!e Urepeatab!eV
T un!essN'e GinputO
TmainBB;rrorN.no fi!e 7Ginput7.O%W
mainBBVerboseN.Parsing 7Ginput78n.O%
T !oca!NGmainBBargKfi!eO%
GmainBBargKfi!e H Ginput%
mainBBVerbose N.finished parsing 7Ginput78n.O%
mainBBVerbose N.returning to 7GmainBBargKfi!e78n.O%
'd )urn debugging 0n
'"erbUoseV )urn "erbose 0n
'/uiet )urn "erbose 0ff
''Dump UundocumentedV Dump on
'h Print Ee!p
'' -rgument separator
Qun,no$nD Fi!ename Urepeatab!eV
T ifNGun,no$n=YmTZU'FVWO
TmainBB;rrorN.un,no$n arg 7Gun,no$n7.O%W
our Gmyparser H ne$ GetoptBBDec!are
1. )ile Input and !utput
Perl has a n)mber o' ')n$tions )sed 'or reading 'rom and -riting to 'iles* ll 'ile I> revolves aro)nd
'ile handles*
1..1 open
/o generate a 'ilehandle and atta$h it to a spe$i'i$ 'ile+ )se the open!& ')n$tion*
openNmy Gfi!ehand!e, 7fi!ename.t*t7O
or die .(ou!d not open fi!e.%
I' the 'irst arg)ment to open!& is an )nde'ined s$alar+ perl -ill $reate a 'ilehandle and assign it to that
s$alar* /his is available in perl version 8*9 and later and is the pre'erred method 'or dealing -ith
/he se$ond arg)ment to open!& is the name o' the 'ile and an optional 'lag that indi$ates to open the 'ile
as read+ -rite+ or append* /he 'ilename is a simple string+ and the 'lag+ i' present+ is the 'irst $hara$ter
o' the string* /he valid 'lags are de'ined as 'ollo-s:
7Q7 @ead. Do not create.
Do not c!obber e*isting fi!e. D;F-UL).
7D7 :rite. (reate if non'e*isting.
(!obber if a!ready e*ists.
7DD7 -ppend. (reate if non'e*isting.
Do not c!obber e*isting fi!e.
I' no 'lag is spe$i'ied+ the 'ile de'a)lts to being opened 'or read*
1..2 close
>n$e open+ yo) $an $lose a 'ilehandle by $alling the $lose ')n$tion and passing it the 'ilehandle*
c!oseNGfi!ehand!eO or die .(ou!d not c!ose.%
I' the 'ilehandle is stored in a s$alar+ and the s$alar goes o)t o' s$ope or is assigned )nde'+ then perl
-ill a)tomati$ally $lose the 'ilehandle 'or yo)*
1..3 read
>n$e open+ yo) $an read 'rom a 'ilehandle a n)mber o' -ays* /he most $ommon is to read the
'ilehandle a line at a time )sing the MangleM operator* /he angle operator is the 'ilehandle s)rro)nded by
angle bra$%ets* i*e* <$filehandle> Ghen )sed as the boolean $onditional $ontrolling a -hile!&
loop+ the loop reads the 'ilehandle a line at a time )ntil the end o' 'ile is rea$hed* 6a$h pass thro)gh the
$onditional test reads the ne(t line 'rom the 'ile and pla$es it in the $_ variable*
/his s$ript sho-s a $at -n style ')n$tion*
open Nmy Gfh, 7input.t*t7O or die .cou!d not open.%
my GnumH5%
$hi!eNQGfhDO T
my G!ine H GK%
print .GnumB G!ine8n.%
/he above e(ample is )se')l i' every line o' the 'ile $ontains the same %ind o' in'ormation+ and yo) are
<)st going thro)gh ea$h line and parsing it*
nother -ay to read 'rom a 'ilehandle is to assign the angle operator o' the 'ilehandle to a s$alar* /his
-ill read the ne(t line 'rom the 'ilehandle* #)t it re;)ires that yo) test the ret)rn val)e to ma%e s)re it
is de'ined+ other-ise yo) hit the end o' 'ile*
definedNmy G!ine H QGfhDO or die .premature eof.%
/o ma%e a little more )se')l+ yo) $an -rap it )p in a s)bro)tine to hide the error $he$%ing* 3o) $an
then $all the s)bro)tine ea$h time yo) -ant a line* /his is )se')l i' yo) are reading a 'ile -here every
line has a di''erent meaning+ and yo) need to read it in a $ertain order*
use (arp%
open Nmy Gfh, 7input.t*t7O%
sub n!in T
definedNmy G!ine HQGfhDO or croa, .premature eof.%
return G!ine%
my GnameHn!in%
my GaddrHn!in%
my Gage Hn!in%
print .NameB Gname, addressB Gaddr, ageB Gage8n.%
1..# write
I' the 'ile is opened 'or -rite or append+ yo) $an -rite to the 'ilehandle )sing the print ')n$tion*
open Nmy Gfh, 7Doutput.t*t7O%
print Gfh .once8n.%
print Gfh .upon8n.%
print Gfh .a time8n.%
c!ose Gfh%
1..) File Tests
Perl $an per'orm tests on a 'ile to glean in'ormation abo)t the 'ile* ll tests ret)rn a tr)e !1& or 'alse !MM&
val)e abo)t the 'ile* ll the tests have the 'ollo-ing synta(:
'* F&L;
/he M(M is a single $hara$ter indi$ating the test to per'orm* "IL6 is a 'ilename !string& or 'ilehandle*
Some $ommon tests in$l)de:
'e fi!e e*ists
'f fi!e is a p!ain fi!e
'd fi!e is a directory
'! fi!e is a symbo!ic !in,
'r fi!e is readab!e
'$ fi!e is $ritab!e
'M fi!e siMe is Mero
'p fi!e is a named pipe
'# fi!e is a soc,et
') fi!e is a te*t fi!e Nper!7s definitionO
1..* File ?lo22ing
/he glob!& ')n$tion ta%es a string e(pression and ret)rns a list o' 'iles that mat$h that e(pression )sing
shell style 'ilename e(pansion and translation*
my ]fi!es H g!ob N #)@&NGK;?P@;##&0N O%
"or e(ample+ i' yo) -ish to get a list o' all the 'iles that end -ith a *t(t e(pression:
my ]te*tfi!es H g!ob N.L.t*t.O%
/his is also )se')l to translate Lin)( style MUM home dire$tories to a )sable 'ile path* /he MUM in Lin)(
is a shell 'eat)re that is translated to the )serRs real dire$tory path )nder the hood* PerlRs open!& ')n$tion
$annot open MU.list*t(tM be$a)se MUM only means something to the shell* /o translate to a real dire$tory
path+ )se glob!&*
my GstartupKfi!e H g!obN7Y/.cshrc7O%
1.., File Tree $earching
"or sophisti$ated sear$hing+ in$l)ding sear$hes do-n an entire dire$tory str)$t)re+ )se the "ile::"ind
mod)le* It is in$l)ded in perl 8*9*1*
use Fi!eBBFind%
my Gp$dH_p$d_%
sub process T ... W
/he pro$ess!& s)bro)tine is a s)bro)tine that yo) de'ine* /he pro$ess!& s)bro)tine -ill be $alled on
every 'ile and dire$tory in Bp-d and re$)rsively into every s)bdire$tory and 'ile belo-*
/he pa$%age variable $File::Find::name $ontains the name o' the $)rrent 'ile or dire$tory* 3o)r
pro$ess!& s)bro)tine $an read this variable and per'orm -hatever testing it -ants on the ')llname* I'
yo) pro$ess!& -as $alled on a 'ile and not <)st a dire$tory+ the path to the 'ile is available in
$File::Find::dir and the name o' the 'ile is in $_* I' yo)r pro$ess!& s)bro)tine sets the pa$%age
variable $File::Find::prune to 1+ then 'ind!& -ill not re$)rse any ')rther into the $)rrent
/his pro$ess!& s)bro)tine prints o)t all *t(t 'iles en$o)ntered and it avoids entering any C7S
sub process T
my Gfu!!name H GFi!eBBFindBBname%
if NGfu!!name HY mT8.t*tGWO
Tprint .found te*t fi!e Gfu!!name8n.%W
ifNN'd Gfu!!nameO and NGfu!!nameHYmT(V#WOO
TGFi!eBBFindBBpruneH1% return%W
"or more in'ormation: perldo$ "ile::"ind
15 !perating S1stem Commands
/-o -ays to iss)e operating system $ommands -ithin yo)r perl s$ript are the system ')n$tion and the
ba$%ti$% operator*
1.systemN.command string.O%
4._command string_%
13.1 The system78 function
I' yo) -ant to e(e$)te some $ommand and yo) do not $are -hat the o)tp)t loo%s li%e+ yo) <)st -ant to
%no- i' it -or%ed+ then yo) -ill li%ely -ant to )se the system!& ')n$tion* /he system!& ')n$tion
e(e$)tes the $ommand string in a shell and ret)rns yo) the ret)rn $ode o' the $ommand* In Lin)(+ a
ret)rn val)e o' [6,> is )s)ally good+ a non-@ero indi$ates some sort o' error* So to )se the system!&
')n$tion and $he$% the ret)rn val)e+ yo) might do something li%e this:
my Gcmd H .rm 'f <un,.t*t.%
systemNGcmdOHH5 or die .;rrorB cou!d not 7Gcmd7.%
Ghen yo) e(e$)te a $ommand via the system!& ')n$tion+ the o)tp)t o' the $ommand goes to S/1>?/+
-hi$h means the )ser -ill see the o)tp)t s$roll by on the s$reen+ and then it is lost 'orever*
13.2 The Bac=tic= ;perator
I' yo) -ant to $apt)re the S/1>?/ o' a operating system $ommand+ then yo) -ill -ant to )se the
ba$%ti$% operator* simple e(ample is the M'ingerM $ommand on Lin)(* I' yo) type:
!inu*D finger username
Lin)( -ill d)mp a b)n$h o' te(t to S/1>?/* I' yo) $all system!& on the 'inger $ommand+ all this te(t
-ill go to S/1>?/ and -ill be seen by the )ser -hen they e(e$)te yo)r s$ript* I' yo) -ant to $apt)re
-hat goes to S/1>?/ and manip)late it -ithin yo)r s$ript+ )se the ba$%ti$% operator*
my GstringKresu!ts H _finger username_%
/he BstringHres)lts variable -ill $ontain all the te(t that -o)ld have gone to S/1>?/* 3o) $an then
pro$ess this in yo)r perl s$ript li%e any other string*
13.3 ;perating $ystem -ommands in a ?:"
I' yo)r perl s$ript is generating a G?I )sing the /% pa$%age+ there is a third -ay to r)n system
$ommands -ithin yo)r perl s$ript+ )sing the /%::6(e$)teCommand mod)le* /his is a very $ool mod)le
that allo-s yo) to r)n system $ommands in the ba$%gro)nd as a separate pro$ess 'rom yo) main perl
s$ript* /he mod)le provides the )ser -ith a MGo.Can$elM b)tton and allo-s the )ser to $an$el the
$ommand in the middle o' e(e$)tion i' it is ta%ing too long*
Ge have not $overed the G?I tool%it 'or perl !/%&+ b)t i' yo) are doing system $ommands in perl and
yo) are )sing /%+ yo) sho)ld loo% into /%::6(e$)teCommand*
26 ,egular @xpressions
,eg)lar e(pressions are the te(t pro$essing -or%horse o' perl* Gith reg)lar e(pressions+ yo) $an
sear$h strings 'or patterns+ 'ind o)t -hat mat$hed the patterns+ and s)bstit)te the mat$hed patterns -ith
ne- strings*
/here are three di''erent reg)lar e(pression operators in perl:
1.match mTP-));@NW
4.substitute sT0LDP-));@NWTN;:P-));@NW
.trans!iterate trT0LDK(E-@K#;)WTN;:K(E-@K#;)W
Perl allo-s any delimiter in these operators+ s)$h as CD or !& or .. or OO or <)st abo)t any $hara$ter yo)
-ish to )se* /he most $ommon delimiter )sed is probably the m.. and s... delimiters+ b)t I pre'er to )se
mCD and sCDCD be$a)se they are $learer 'or me* /here are t-o -ays to MbindM these operators to a string
1.HY pattern does match string e*pression
4.=Y pattern does N0) match string e*pression
#inding $an be tho)ght o' as M>b<e$t >riented ProgrammingM 'or reg)lar e(pressions* Generi$ >>P
str)$t)re $an be represented as
Gsub<ect 'D "erb N ad<ecti"es, ad"erbs, etc O%
#inding in ,eg)lar 6(pressions $an be loo%ed at in a similar 'ashion:
Gstring HY "erb N pattern O%
-here MverbM is limited to RmR 'or mat$h+ RsR 'or s)bstit)tion+ and RtrR 'or translate* 3o) may see perl $ode
that simply loo%s li%e this:
/his is ')n$tionally e;)ivalent to this:
GK HY m/patt/%
4ere are some e(amples:
A spam fi!ter
my Gemai! H .)his is a great Free 0ffer8n.%
ifNGemai! HY mTFree 0fferWO
TGemai!H.Lde!eted spamL8n.% W
print .Gemai!8n.%
A upgrade my car
my Gcar H .my car is a toyota8n.%
Gcar HY sTtoyotaWT<aguarW%
print .Gcar8n.%
A simp!e encryption, (aesar cypher
my G!o"eK!etter H .Eo$ & !o"e thee.8n.%
G!o"eK!etter HY trT-'`a'MWTN'`-'Cn'Ma'mW%
print .encryptedB G!o"eK!etter.%
G!o"eK!etter HY trT-'`a'MWTN'`-'Cn'Ma'mW%
print .decryptedB G!o"eK!etter8n.%
D Lde!eted spamL
D my car is a <aguar
D encryptedB Ub< V ybir gurr.
D decryptedB Eo$ & !o"e thee.
/he above e(amples all loo% 'or 'i(ed patterns -ithin the string* ,eg)lar e(pressions also allo- yo) to
loo% 'or patterns -ith di''erent types o' M-ild$ardsM*
20.1 'aria2le "nterpolation
/he bra$es that s)rro)nd the pattern a$t as do)ble-;)ote mar%s+ s)b<e$ting the pattern to one pass o'
variable interpolation as i' the pattern -ere $ontained in do)ble-;)otes* /his allo-s the pattern to be
$ontained -ithin variables and interpolated d)ring the reg)lar e(pression*
my Gactua! H .)oyota.%
my G$anted H .9aguar.%
my Gcar H .Cy car is a )oyota8n.%
Gcar HY sTGactua!WTG$antedW%
print Gcar%
D Cy car is a 9aguar
20.2 >ildcard &9ample
In the e(ample belo-+ -e pro$ess an array o' lines+ ea$h $ontaining the pattern C'ilename: D 'ollo-ed
by one or more non--hitespa$e $hara$ters 'orming the a$t)al 'ilename* 6a$h line also $ontains the
pattern Csi@e: D 'ollo-ed by one or more digits that indi$ate the a$t)al si@e o' that 'ile*
my ]!ines H sp!it .8n., QQ.C-@^;@.
fi!enameB output.t*t siMeB 154I
fi!enameB input.dat siMeB J14
fi!enameB address.db siMeB 15IPJ3R
foreach my G!ine N]!inesO T
A 8# is a $i!dcard meaning
A .anything that is not $hite'space..
A the .F. means .one or more.
ifNG!ine HY mTfi!enameB N8#FOWO T
my Gname H G1%
A 8d is a $i!dcard meaning
A .any digit, 5'6..
G!ine HY mTsiMeB N8dFOW%
my GsiMe H G1%
print .Gname,GsiMe8n.%
D output.t*t,154I
D input.dat,J14
D address.db,15IPJ3R
20.3 Defining a !attern
pattern $an be a literal pattern s)$h as {Free Offer}. It $an $ontain -ild$ards s)$h as {\d}* It
$an also $ontain meta$hara$ters s)$h as the parenthesis* =oti$e in the above e(ample+ the parenthesis
-ere in the pattern b)t did not o$$)r in the string+ yet the pattern mat$hed*
20.# +etacharacters
:eta$hara$ters do not get interpreted as literal $hara$ters* Instead they tell perl to interpret the
meta$hara$ter !and sometimes the $hara$ters aro)nd meta$hara$ter& in a di''erent -ay* /he 'ollo-ing
are meta$hara$ters in perl reg)lar e(pression patterns:
\ | ( ) [ ] { } ^ $ * + ? .
!ba$%slash& i' ne(t $hara$ter $ombined -ith this ba$%slash 'orms a $hara$ter $lass
short$)t+ then mat$h that $hara$ter $lass* I' not a short$)t+ then simply treat ne(t
$hara$ter as a non-meta$hara$ter*
alternation: !patt1 Y patt2& means !patt1 >, patt2&
( )
gro)ping !$l)stering& and $apt)ring
(?: )
gro)ping !$l)stering& only* no $apt)ring* !some-hat 'aster&
mat$h any single $hara$ter !)s)ally not MLnM&
[ ]
de'ine a $hara$ter $lass+ mat$h any single $hara$ter in $lass
!;)anti'ier&: mat$h previo)s item @ero or more times
!;)anti'ier&: mat$h previo)s item one or more times
!;)anti'ier&: mat$h previo)s item @ero or one time
{ }
!;)anti'ier&: mat$h previo)s item a n)mber o' times in given range
!position mar%er&: beginning o' string !or possibly a'ter MLnM&
!position mar%er&: end o' string !or possibly be'ore MLnM&
6(amples belo-* Change the val)e assigned to Bstr and re-r)n the s$ript* 6(periment -ith -hat
mat$hes and -hat does not mat$h the di''erent reg)lar e(pression patterns*
my Gstr H .Dear sir, he!!o and goodday= .
.. dogs and cats and sssna,es put me to s!eep..
.. MMMM. Eummingbirds are ffffast. .
.. #incere!y, 9ohn.%
A \ a!ternation
A match .he!!o. or .goodbye.
ifNGstr HY mThe!!o\goodbyeWOT$arn .a!t.%W
A NO grouping and capturing
A match 7goodday7 or 7goodbye7
ifNGstr HY mTNgoodNday\byeOOWO
T$arn .group matched, captured 7G17.%W
A . any sing!e character
A match 7cat7 7cbt7 7cct7 7cSt7 7cFt7 7cXt7 ...
ifNGstr HY mTc.tWOT$arn .period.%W
A UV define a character c!assB 7a7 or 7o7 or 7u7
A match 7cat7 7cot7 7cut7
ifNGstr HY mTcUaouVtWOT$arn .c!ass.%W
A L /uantifier, match pre"ious item Mero or more
A match 77 or 7M7 or 7MM7 or 7MMM7 or 7MMMMMMMM7
ifNGstr HY mTMLWOT$arn .asteris,.%W
A F /uantifier, match pre"ious item one or more
A match 7sna,e7 7ssna,e7 7sssssssna,e7
ifNGstr HY mTsFna,eWOT$arn .p!us sign.%W
A X /uantifier, pre"ious item is optiona!
A match on!y 7dog7 and 7dogs7
ifNGstr HY mTdogsXWOT$arn ./uestion.%W
A TW /uantifier, match pre"ious, QH /ty QH J
A match on!y 7fffast7, 7ffffast7, and 7fffffast7
ifNGstr HY mTfT,JWastWOT$arn .cur!y brace.%W
A Z position mar,er, matches beginning of string
A match 7Dear7 on!y if it occurs at start of string
ifNGstr HY mTZDearWOT$arn .caret.%W
A G position mar,er, matches end of string
A match 79ohn7 on!y if it occurs at end of string
ifNGstr HY mT9ohnGWOT$arn .do!!ar.%W
D a!t at ...
D group matched, captured 7goodday7 at ...
D period at ...
D c!ass at ...
D asteris, at ...
D p!us sign at ...
D /uestion at ...
D cur!y brace at ...
D caret at ...
D do!!ar at ...
20.) -apturing and -lustering !arenthesis
=ormal parentheses -ill both $l)ster and $apt)re the pattern they $ontain* Cl)stering a''e$ts the order
o' eval)ation similar to the -ay parentheses a''e$t the order o' eval)ation -ithin a mathemati$al
e(pression* =ormally+ m)ltipli$ation has a higher pre$eden$e than addition* /he e(pression M2 W 2 _ 4M
does the m)ltipli$ation 'irst and then the addition+ yielding the res)lt o' M14M* /he e(pression M!2 W 2& _
4M 'or$es the addition to o$$)r 'irst+ yielding the res)lt o' M20M*
Cl)stering parentheses -or% in the same 'ashion* /he pattern C$atsZD -ill apply the MZM ;)anti'ier to
the letter MsM+ mat$hing either M$atM or M$atsM* /he pattern C!$ats&ZD -ill apply the MZM ;)anti'ier to the
entire pattern -ithin the parentheses+ mat$hing M$atsM or n)ll string*
26.&.1 713 723 733 etc Capturing parentheses
Cl)stering parentheses -ill also Capt)re the part o' the string that mat$hed the pattern -ithin
parentheses* /he $apt)red val)es are a$$essible thro)gh some Mmagi$alM variables $alled B1+ B2+ B2+ ***
6a$h le't parenthesis in$rements the n)mber )sed to a$$ess the $apt)red string* /he le't parenthesis are
$o)nted 'rom le't to right as they o$$)r -ithin the pattern+ starting at 1*
my GtestH.FirstnameB 9ohn LastnameB #mith.%
A G1 G4
GtestHYmTFirstnameB N8$FO LastnameB N8$FOW%
my Gfirst H G1%
my G!ast H G4%
print .Ee!!o, Gfirst G!ast8n.%
D Ee!!o, 9ohn #mith
#e$a)se $apt)ring ta%es a little e(tra time to store the $apt)red res)lt into the B1+ B2+ ` variables+
sometimes yo) <)st -ant to $l)ster -itho)t the overhead o' $apt)ring* In the belo- e(ample+ -e -ant
to $l)ster MdayYbyeM so that the alternation symbol MYM -ill go -ith MdayM or MbyeM* Githo)t the
$l)stering parenthesis+ the pattern -o)ld mat$h MgooddayM or MbyeM+ rather than MgooddayM or
MgoodbyeM* /he pattern $ontains $apt)ring parens aro)nd the entire pattern+ so -e do not need to
$apt)re the MdayYbyeM part o' the pattern+ there'ore -e )se $l)ster-only parentheses*
ifNGstr HY mTNgoodNXBday\byeOOWO
T$arn .group matched, captured 7G17.%W
Cl)ster-only parenthesis donRt $apt)re the en$losed pattern+ and they donRt $o)nt -hen determining
-hi$h magi$ variable+ B1+ B2+ B2 ***+ -ill $ontain the val)es 'rom the
$apt)ring parentheses*
my Gtest H 7goodday 9ohn7%
A G1 G4
ifNGtest HY mTNgoodNXBday\byeOO N8$FOWO
T print .>ou said G1 to G48n.% W
D >ou said goodday to 9ohn
26.&.2 Capturing parentheses not capturing
I' a reg)lar e(pression $ontaining $apt)ring parentheses does not mat$h the string+ the magi$ variables
B1+ B2+ B2+ et$ -ill retain -hatever P,67I>?S val)e they had 'rom any P,67I>?S reg)lar
e(pression* /his means that yo) :?S/ $he$% to ma%e s)re the reg)lar e(pression mat$hes #6">,6
yo) )se the B1+ B2+ B2+ et$ variables*
In the e(ample belo-+ the se$ond reg)lar e(pression does not mat$h+ there'ore B1 retains its old val)e
o' RbeR* Instead o' printing o)t something li%e M=ame is 4oratioM or M=ame isM and 'ailing on an
)nde'ined val)e+ perl instead %eeps the old val)e 'or B1 and prints M=ame is RbeRM+ instead*
my Gstring1 H 7)o be, or not to be7%
Gstring1 HY mTnot to N8$FOW% A matches, G1H7be7
$arn .)he /uestion is to G1.%
my Gstring4 H 7that is the /uestion7%
Gstring4 HY mT& ,ne$ him once, N8$FOW% A no match
$arn .Name is 7G17.%
A no match, so G1 retains its o!d "a!ue 7be7
D )he /uestion is to be at ./script.p! !ine 3.
D Name is 7be7 at ./script.p! !ine 11.
20.* -haracter -lasses
/he M*M meta$hara$ter -ill mat$h any single $hara$ter* /his is e;)ivalent to a $hara$ter $lass that
in$l)des every possible $hara$ter* 3o) $an easily de'ine smaller $hara$ter $lasses o' yo)r o-n )sing
the s;)are bra$%ets \]* Ghatever $hara$ters are listed -ithin the s;)are bra$%ets are part o' that
$hara$ter $lass* Perl -ill then mat$h any one $hara$ter -ithin that $lass*
Uaeiou-;&0UV any "o$e!
U514IJR3P6V any digit
26.+.1 =etacharacters Aithin Character Classes
Githin the s;)are bra$%ets )sed to de'ine a $hara$ter $lass+ all previo)sly de'ined meta$hara$ters $ease
to a$t as meta$hara$ters and are interpreted as simple literal $hara$ters* Chara$ters $lasses have their
o-n spe$ial meta$hara$ters*
L !ba$%slash& demeta the ne(t $hara$ter
- !hyphen& Indi$ates a $onse$)tive $hara$ter range+ in$l)sively*
\a-'] indi$ates the letters a+b+$+d+e+'*
Chara$ter ranges are based o'' o' SCII n)meri$ val)es*
a I' it is the 'irst $hara$ter o' the $lass+ then this indi$ates the $lass
is any $hara$ter 6NC6P/ the ones in the s;)are bra$%ets*
Garning: \aaeio)] means anything b)t a lo-er $ase vo-el* /his
is not the same as Many $onsonantM* /he $lass \aaeio)] -ill
mat$h p)n$t)ation+ n)mbers+ and )ni$ode $hara$ters*
20., $hortcut -haracter -lasses
Perl has short$)t $hara$ter $lasses 'or some more $ommon $lasses*
shortcut class description
Ld \0-9]
any digit
L1 \a0-9] any =>=-digit
Ls \ LtLnLrL']
any -hitespa$e
LS \a LtLnLrL'] any =>=--hitespa$e
L- \a-@-[0-9H]
any word $hara$ter !valid perl identi'ier&
LG \aa-@-[0-9H] any =>=--ord $hara$ter
20.. ?reedy 7+a9imal8 Guantifiers
K)anti'iers are )sed -ithin reg)lar e(pressions to indi$ate ho- many times the previo)s item o$$)rs
-ithin the pattern* #y de'a)lt+ ;)anti'iers are MgreedyM or Mma(imalM+ meaning that they -ill mat$h as
many $hara$ters as possible and still be tr)e*
_ mat$h @ero or more times !mat$h as m)$h as possible&
W mat$h one or more times !mat$h as m)$h as possible&
Z mat$h @ero or one times !mat$h as m)$h as possible&
C$o)ntD mat$h e(a$tly M$o)ntM times
Cmin+ D mat$h at least MminM times !mat$h as m)$h as possible&
Cmin+ma(D mat$h at least MminM and at most Mma(M times
(match as much as possible)
20.3 Thrifty 7+inimal8 Guantifiers
Pla$ing a MZM a'ter a ;)anti'ier disables greediness+ ma%ing them Mnon-greedyM+ Mthri'tyM+ or MminimalM
;)anti'iers* :inimal ;)anti'iers mat$h as 'e- $hara$ters as possible and still be tr)e*
_Z mat$h @ero or more times
!mat$h as little as possible and still be tr)e&
WZ mat$h one or more times
!mat$h as little as possible and still be tr)e&
Cmin+DZ mat$h at least min times
!mat$h as little as possible and still be tr)e&
Cmin+ ma(DZ mat$h at least MminM and at most Mma(M times
!mat$h as little as possible and still be tr)e&
/his e(ample sho-s the di''eren$e bet-een minimal and ma(imal ;)anti'iers*
my Gstring H .14I5555.%
ifNGstring HY mTZN8dFO5FGWO
T print .greedy 7G178n.% W
ifNGstring HY mTZN8dFXO5FGWO
T print .thrifty 7G178n.% W
D greedy 714I5557
D thrifty 714I7
20.10 !osition /ssertions @ !osition /nchors
Inside a reg)lar e(pression pattern+ some symbols do not translate into a $hara$ter or $hara$ter $lass*
Instead+ they translate into a MpositionM -ithin the string* I' a position an$hor o$$)rs -ithin a pattern+
the pattern be'ore and a'ter that an$hor m)st o$$)r -ithin a $ertain position -ithin the string*
a :at$hes the beginning o' the string*
I' the .m !m)ltiline& modi'ier is present+ mat$hes MLnM also*
B :at$hes the end o' the string*
I' the .m !m)ltiline& modi'ier is present+ mat$hes MLnM also*
L :at$h the beginning o' string only* =ot a''e$ted by .m modi'ier*
L@ :at$h the end o' string only* =ot a''e$ted by .m modi'ier*
L[ :at$hes the end o' the string only+ b)t -ill $homp!& a MLnM i' that
-as the last $hara$ter in string*
Lb -ord MbMo)ndary
-ord bo)ndary o$$)rs in 'o)r pla$es*
1& at a transition 'rom a L- $hara$ter to a LG $hara$ter
2& at a transition 'rom a LG $hara$ter to a L- $hara$ter
2& at the beginning o' the string
4& at the end o' the string
L# =>/ Lb
LG )s)ally )sed -ith .g modi'ier !probably -ant .$ modi'ier too&*
Indi$ates the position a'ter the $hara$ter o' the last pattern mat$h
per'ormed on the string* I' this is the 'irst reg)lar e(pression begin
per'ormed on the string then LG -ill mat$h the beginning o' the
string* ?se the pos!& ')n$tion to get and set the $)rrent LG position
-ithin the string*
26.16.1 The Bb *nchor
?se the Lb an$hor -hen yo) -ant to mat$h a -hole -ord pattern b)t not part o' a -ord* /his e(ample
mat$hes M<)mpM b)t not M<)mpropeM:
my Gtest1H7Ee can <ump "ery high.7%
T print .test1 matches8n.% W
my Gtest4H7Pic, up that <umprope.7%
T print .test4 does not match8n.% W
D test1 matches
D test4 does not match
26.16.2 The B< *nchor
/he LG an$hor is a sophisti$ated an$hor )sed to per'orm a progression o' many reg)lar e(pression
pattern mat$hes on the same string* /he LG an$hor represents the position -ithin the string -here the
previo)s reg)lar e(pression 'inished* /he 'irst time a reg)lar e(pression is per'ormed on a string+ the LG
an$hor represents the beginning o' the string*
/he lo$ation o' the LG an$hor -ithin a string $an be determined by $alling the pos!& ')n$tion on the
string* /he pos!& ')n$tion -ill ret)rn the $hara$ter inde( in the string !inde( @ero is to the le't o' the
'irst $hara$ter in the string& representing the lo$ation o' the LG an$hor* ssigning to pos!Bstr& -ill
$hange the position o' the LG an$hor 'or that string*
/he LG an$hor is )s)ally )sed -ith the M$gM modi'iers* /he M$gM modi'iers tell perl to =>/ reset the LG
an$hor to @ero i' the reg)lar e(pression 'ails to mat$h* /his -ill allo- a series o' reg)lar e(pressions to
operate on a string+ )sing the LG an$hor to indi$ate the lo$ation -here the previo)s reg)lar e(pression
'inished* Githo)t the M$gM modi'iers+ the 'irst reg)lar e(pression that 'ails to mat$h -ill reset the LG
an$hor ba$% to @ero*
/he e(ample belo- )ses the LG an$hor to e(tra$t bits o' in'ormation 'rom a single string* 'ter every
reg)lar e(pression+ the s$ript prints the pos!& val)e o' the string* =oti$e ho- the pos!& val)e %eeps
my Gstr H .FirstnameB 9ohn LastnameB #mith
+oo,co!!ectionB Programming Per!, Per! (oo,boo,,
&mpatient Per!.%
ifNGstrHYmT8GFirstnameB N8$FO WcgO T
my Gfirst H G1%
print .pos is ..posNGstrO..8n.%
ifNGstrHYmT8GLastnameB N8$FO WcgO T
my G!ast H G1%
print .pos is ..posNGstrO..8n.%
GstrHYmT8G+oo,co!!ectionB Wcg%
$hi!eNGstrHYmT8G8sLNUZ,VFO,XWcgO T
print .boo, is 7G178n.%
print .pos is ..posNGstrO..8n.%
D pos is 1R
D pos is 4
D boo, is 7Programming Per!7
D pos is RJ
D boo, is 7Per! (oo,boo,7
D pos is P5
D boo, is 7&mpatient Per!7
D pos is 6J
nother -ay to $ode the above s$ript is to )se s)bstit)tion reg)lar e(pressions and s)bstit)te ea$h
mat$hed part -ith empty strings* /he problem is that a s)bstit)tion $reates a ne- string and $opies the
remaining $hara$ters to that string+ res)lting in a m)$h slo-er s$ript* In the above e(ample+ the speed
di''eren$e -o)ld not be noti$eable to the )ser+ b)t i' yo) have a s$ript that is parsing thro)gh a lot o'
te(t+ the di''eren$e $an be ;)ite signi'i$ant*
20.11 +odifiers
,eg)lar e(pressions $an ta%e optional modi'iers that tell perl additional in'ormation abo)t ho- to
interpret the reg)lar e(pression* :odi'iers are pla$ed a'ter the reg)lar e(pression+ o)tside any $)rly
Gstr HY mTpatternWmodifiers%
Gstr HY sTo!dpattWTne$pattWmodifiers%
Gstr HY trTo!dsetWTne$setWmodifiers%
26.11.1 <lobal =odifiers
/he 'ollo-ing modi'iers $an be )sed -ith mCD+ sCDCD+ or trCDCD*
i $ase Insensitive+ mC$atDi mat$hes $at+ Cat+ Ca/+ Ct+ C/+ et$
( ignore spa$es and tabs and $arriage ret)rns in pattern* /his
allo-s the pattern to be spread o)t over m)ltiple lines and 'or
reg)lar perl $omments to be inserted -ithin the pattern b)t be
ignored by the reg)lar e(pression engine*
s treat string as a Single line*
M*M -ill mat$h MLnM -ithin the string*
a and B position an$hors -ill only mat$h literal beginning and
end o' string*
m treat string as :)ltiple lines* !16"?L/&
M*M -ill =>/ mat$h MLnM
a and B position an$hors -ill mat$h literal beginning and end o'
string and also MLnM $hara$ters -ithin the string*
a and B indi$ate start.end o' MlineM instead o' start.end o' string*
a mat$hes a'ter MLnM
B mat$hes be'ore MLnM
o $ompile the pattern >n$e* possible speed improvement*
26.11.2 The m *nd s =odifiers
/he de'a)lt behavior o' perl reg)lar e(pressions is MmM+ treating strings as a m)ltiple lines* I' neither a
MmM or MsM modi'ier is )sed on a reg)lar e(pression+ perl -ill de'a)lt to MmM behavior*
I' the MmM modi'ier is )sed+ then the MaM an$hor -ill mat$h the beginning o' the string or MLnM
$hara$ters+ the MBM an$hor -ill mat$h the end o' the string or any MLnM $hara$ters+ and the M*M $hara$ter
set -ill mat$h any $hara$ter 6NC6P/ MLnM* I' a string $ontains m)ltiple lines separated by MLnM+ then
the de'a)lt behavior !the MmM behavior& is to treat the string as m)ltiple lines+ )sing MaM and MBM to
indi$ate start and end o' lines*
I' the MsM modi'ier is )sed+ then the MaM an$hor -ill only mat$h the literal beginning o' the string+ the
MBM an$hor -ill only mat$h the literal end o' string+ and the M*M $lass -ill mat$h any $hara$ter in$l)ding
MLnM* Gith the MsM modi'ier+ even i' the string is m)ltiple lines -ith embedded MLnM $hara$ters+ the MsM
modi'ier 'or$es perl to treat it as a single line*
/his e(ample sho-s the e(a$t same pattern bo)nd to the e(a$t same string* /he only di''eren$e is the
modi'ier )sed on the reg)lar e(pression* =oti$e in the MsM version+ the $apt)red string in$l)des the
ne-line MLnM $hara$ters -hi$h sho-s )p in the printed o)tp)t* /he single line version prints o)t the
$apt)red pattern a$ross three di''erent lines*
my Gstring H .LibraryB Programming Per! 8n.
..Per! (oo,boo,8n.
..&mpatient Per!.%
ifNGstring HY mTLibraryB N.LOWO
T print .defau!t is 7G178n.% W
ifNGstring HY mTLibraryB N.LOWmO
T print .mu!ti!ine is 7G178n.% W
ifNGstring HY mTLibraryB N.LOWsO
T print .sing!e!ine is 7G178n.% W
D defau!t is 7Programming Per! 7
D mu!ti!ine is 7Programming Per! 7
D sing!e!ine is 7Programming Per!
D Per! (oo,boo,
D &mpatient Per!7
26.11.3 The x =odifier
/he ( modi'ier allo-s a $omple( reg)lar e(pression pattern to be spread o)t over m)ltiple lines+ -ith
$omments+ 'or easier reading* :ost -hitespa$e -ithin a pattern -ith the ( modi'ier is ignored* /he
'ollo-ing pattern is loo%ing 'or a n)mber that 'ollo-s s$ienti'i$ notation* /he pattern is spread o)t over
m)ltiple lines -ith $omments to s)pport maintainability*
my Gstring H 7' 1I.4I4 e '147%
ifN Gstring HY m
Z 8sL NU'FVXO A positi"e or negati"e or optiona!
8sL N 8dF O A integer portion
N 8. 8dF OX A fractiona! is optiona!
N 8sL e 8sL UF'VX 8dFOX A e*ponent is optiona!
W* O T
my Gsign H G1 \\ 77%
my Ginteger H G4 \\ 77%
my Gfraction H G \\ 77%
my Ge*ponent H GI \\ 77%
print .sign is 7Gsign78n.%
print .integer is 7Ginteger78n.%
print .fraction is 7Gfraction78n.%
print .e*ponent is 7Ge*ponent78n.%
D sign is 7'7
D integer is 71I7
D fraction is 7.4I47
D e*ponent is 7 e '147
$o)ple o' notes 'or the above e(ample: /he ( modi'ier strips o)t all spa$es+ tabs+ and $arriage ret)rns
in the pattern* I' the pattern e(pe$ts -hitespa$e in the string+ it m)st be e(pli$itly stated )sing Ls or Lt
or Ln or some similar $hara$ter $lass* lso+ itRs al-ays a good idea to an$hor yo)r reg)lar e(pression
some-here in yo)r string+ -ith MaM or MBM or MLGM* /he do)ble-pipe e(pressions g)arantee that the
variables are assigned to -hatever the pattern mat$hed or empty string i' no mat$h o$$)rred* Githo)t
them+ an )nmat$hed pattern mat$h -ill yield an M)nde'M in the B1 !or B2 or B2& variable asso$iated -ith
the mat$h*
20.12 +odifiers For mHI ;perator
/he 'ollo-ing modi'iers apply to the mCpatternD operator only:
g Globally 'ind all mat$hs* Githo)t this modi'ier+ mCD -ill 'ind
the 'irst o$$)rren$e o' the pattern*
$g Contin)e sear$h a'ter Global sear$h 'ails* /his maintains the LG
mar%er at its last mat$hed position* Githo)t this modi'ier+ the LG
mar%er is reset to @ero i' the pattern does not mat$h*
20.13 +odifiers for sHIHI ;perator
/he 'ollo-ing modi'iers apply to the sColdpattDCne-pattD operator only*
g Globally repla$e all o$$)rren$es o' oldpatt -ith ne-patt
e interpret ne-patt as a perl-based string 6(pression*
the res)lt o' the e(pression be$omes the repla$ement string*
20.1# +odifiers for trHIHI ;perator
/he 'ollo-ing modi'iers apply to the trColdsetDCne-setD operator only*
$ Complement the sear$hlist
d 1elete 'o)nd b)t )nrepla$ed $hara$ters
s S;)ash d)pli$ate repla$ed $hara$ters
20.1) The 1rHI function
/he ;rCD ')n$tion ta%es a string and interprets it as a reg)lar e(pression+ ret)rning a val)e that $an be
stored in a s$alar 'or pattern mat$hing at a later time*
my Gnumber H /rTUF'VX8sL8dFNXB8.8dFOX8sLNXBe8sLUF'VX8sL8dFOXW%
20.1* -ommon !atterns
Some simple and $ommon reg)lar e(pression patterns are sho-n here:
Gstr HY sT8sWTWg% A remo"e a!! $hitespace
Gstr HY sTA.LWTW% A remo"e per! comments
ne*t ifNGstr HY mTZ8sLGWO%A ne*t if on!y $hitespace
"or $ommon b)t more $ompli$ated reg)lar e(pressions+ $he$% o)t the ,ege(p::Common mod)le on
20.1, (ege9pFF-ommon
/he ,ege(p::Common mod)le $ontains many $ommon+ b)t 'airly $ompli$ated+ reg)lar e(pression
patterns !balan$ed parentheses and bra$%ets+ delimited te(t -ith es$apes+ integers and 'loating point
n)mbers o' di''erent bases+ email addresses+ and others&* I' yo) are doing some $ompli$ated pattern
mat$hing+ it might be -orth a moment to $he$% o)t ,ege(p::Common and see i' someone already did
the -or% to mat$h the pattern yo) need*
cpanD insta!! @ege*pBB(ommon
>n$e ,ege(p::Common is installed+ perl s$ripts that )se it -ill have a Mmagi$M hash $alled E,6
imported into their namespa$e* /he %eys to this hash are h)man )nderstandable names+ the data in the
hash are the patterns to )se -ithin reg)lar e(pressions*
4ere is ho- to 'ind o)t -hat the 'loating point n)mber pattern loo%s li%e in ,ege(p::Common:
use @ege*pBB(ommon%
my Gpatt H G@;TnumWTrea!W%
print .Gpatt8n.%
s $ompli$ated as this is+ it is a lot easier to re)se someone elseRs $ode than to try and reinvent yo)r
o-n+ 'a)lty+ lopsided+ -heel*
/he hash loo%)p $an be )sed dire$tly -ithin yo)r reg)lar e(pression:
use @ege*pBB(ommon%
my Gstr H .this is '14.I4;'I4 the number.%
Gstr HY mTNG@;TnumWTrea!WOW%
print .match is 7G178n.%
D match is 7'14.I4;'I47
21 Parsing "ith Parse??,ec'escent
PerlRs reg)lar e(pression patterns are s)''i$ient 'or many sit)ations+ s)$h as e(tra$ting in'ormation o)t
o' a tab separated database that is organi@ed by lastname+ 'irstname+ dateo'-birth+ address+ $ity+ state+
[IP+ phonen)mber* /he data is al-ays in a 'i(ed lo$ation+ and a reg)lar e(pression $an be )sed to
per'orm sear$hes -ithin that data*
I' the data being parsed is not ;)ite so rigid in its de'inition+ reg)lar e(pressions may be$ome a
$)mbersome means to e(tra$t the desired data* Instead+ the Parse::,e$1es$ent mod)le may prove
)se')l in that it allo-s -hole gramati$al r)les to be de'ined+ and the mod)le parses the data a$$ording
to those r)les*
cpanD insta!! ParseBB@ecDescent
Parse::,e$1es$ent des$ribes itsel' as a mod)le that in$rementally generates top-do-n re$)rsive-
des$ent te(t parsers 'rom simple ya$$-li%e grammar spe$i'i$ations* In simpler terms+ Parse::,e$1es$ent
)ses reg)lar e(pression styled patterns to de'ine grammar r)les+ and these r)les $an be $ombined 'airly
easily to $reate $omple( r)les*
4ere is a ;)i$% e(ample 'rom perldo$ Parse::,e$1es$ent
use ParseBB@ecDescent%
print .try typing these !inesB8n.%
print .Ee7s dead, 9im=8n.%
print .Dammit, 9im, &7m a doctor, not a
print .press Q()LDQDD $hen finished8n.%
my Ggrammar H /T
curse .,. name ., &7m a doctor, not a. <ob .=.
T print .9ust do $hat you can, +ones.8n.% W
\ pronoun .dead,. name .=.
T print .#hut up, +ones.8n.%W
\ QerrorD
curseB 7Dammit7 \ 7Goddammit7
nameB 79im7 \ 7#poc,7 \ 7#cotty7
<obB 7magician7 \ 7mirac!e $or,er7 \ 7per! hac,er7
pronounB .Ee7s. \ .#he7s. \ .&t7s. \ .)hey7re.
my Gparse H ne$ ParseBB@ecDescentNGgrammarO%
print .D .%
$hi!eNQDO T
print .D .%
D try typing these !inesB
D Ee7s dead, 9im=
D Dammit, 9im, &7m a doctor, not a magician=
D press Q()LDQDD $hen finished
D D Dammit, 9im, &7m a doctor, not a magician=
D 9ust do $hat you can, +ones.
D D Ee7s dead, 9im=
D #hut up, +ones.
D D >ou green b!ooded Vu!can=
D ;@@0@ N!ine 1OB &n"a!id Cc(oyB
D :as e*pecting curse, or pronoun
Parse::,e$1es$ent is not the sol)tion 'or every pattern mat$hing problem* Parse::,e$1es$ent is slo-er
than simple reg)lar e(pressions* Sin$e it re$)rsively des$ends thro)gh its set o' r)les+ the more r)les+
the longer it ta%es to r)n* Parse::,e$1es$ent $)rrently m)st read in the entire te(t being parsed+ -hi$h
$an be a problem i' yo) are parsing a gigabyte-si@ed 'ile* nd Parse::,e$1es$ent has an additional
learning $)rve above and beyond perlRs reg)lar e(pressions* Parse::,e$1es$ent )ses perlMs reg)lar
e(pression patterns in its pattern mat$hing+ so yo) need to learn basi$ reg)lar e(pression patterns
be'ore yo) )se Parse::,e$1es$ent*
I' the data yo) are mining is 'airly $omple(+ and normal reg)lar e(pressions are be$oming di''i$)lt to
manage+ then Parse::,e$1es$ent -o)ld be the ne(t logi$al mod)le to loo% at*
22 Perl3 <$I3 and T9
So 'ar+ all the e(amples have had a $ommand line inter'a$e* ?ser inp)t and o)tp)t o$$)rred thro)gh the
same $ommand line )sed to e(e$)te the perl s$ript itsel'* Perl has a Graphi$al ?ser Inter'a$e !G?I&
tool%it mod)le available on CP= $alled /%*
cpanD insta!! ),
/he /% mod)le is a G?I tool%it that $ontains a plethora o' b)ttons and labels and entry items and other
-idgets needed to $reate a graphi$al )ser inter'a$e to yo)r s$ripts* >n$e installed+ the /% mod)le has a
-idget demonstration program that $an be r)n 'rom the $ommand line to see -hat -idgets are available
and -hat they loo% li%e* t the $ommand line+ type M-idgetM to r)n the demonstration program*
D $idget
4ere is a simple Mhello -orldM style program )sing /%:
use ),%
my GtopHne$ Cain:indo$%
Gtop'D+utton N
'commandHDsubTprint .Ei8n.%W
Ghen the above e(ample is e(e$)ted+ a small G?I -ill pop)p on the s$reen !the :ainGindo- item&
-ith a b)tton !the Btop-I#)tton $all& labeled M4elloM !the -te(t option&* Ghen the mo)se le't-$li$%s on
the b)tton+ the -ord M4iM is printed to the $ommand line !the -$ommand option&* /he -Igrid method
invo%es the geometry manager on the -idget and pla$es it some-here in the G?I !-itho)t geometry
management+ the -idget -ill not sho- )p in the G?I&* /he :ainLoop is a s)bro)tine $all that invo%es
the event loop+ dra-ing the G?I+ responding to b)tton $li$%s+ et$*
Several large boo%s have been -ritten abo)t the /% G?I tool%it 'or perl* nd it -o)ld be impossible to
give any de$ent introd)$tion to this mod)le in a page or t-o* I' yo) plan on $reating G?IRs in yo)r
s$ripts+ I re$ommend the M:astering Perl./%M boo%*
23 <N$ )ree 'ocumentation 4icense
GNU Free Documentation License
Version 1., No"ember 455P
(opyright N(O 4555, 4551, 4554, 4553, 455P Free #oft$are Foundation, &nc.
;"eryone is permitted to copy and distribute "erbatim copies
of this !icense document, but changing it is not a!!o$ed.
5. P@;-C+L;
)he purpose of this License is to ma,e a manua!, te*tboo,, or other
functiona! and usefu! document .free. in the sense of freedomB to
assure e"eryone the effecti"e freedom to copy and redistribute it,
$ith or $ithout modifying it, either commercia!!y or noncommercia!!y.
#econdari!y, this License preser"es for the author and pub!isher a $ay
to get credit for their $or,, $hi!e not being considered responsib!e
for modifications made by others.
)his License is a ,ind of .copy!eft., $hich means that deri"ati"e
$or,s of the document must themse!"es be free in the same sense. &t
comp!ements the GNU Genera! Pub!ic License, $hich is a copy!eft
!icense designed for free soft$are.
:e ha"e designed this License in order to use it for manua!s for free
soft$are, because free soft$are needs free documentationB a free
program shou!d come $ith manua!s pro"iding the same freedoms that the
soft$are does. +ut this License is not !imited to soft$are manua!s%
it can be used for any te*tua! $or,, regard!ess of sub<ect matter or
$hether it is pub!ished as a printed boo,. :e recommend this License
principa!!y for $or,s $hose purpose is instruction or reference.
1. -PPL&(-+&L&)> -ND D;F&N&)&0N#
)his License app!ies to any manua! or other $or,, in any medium, that
contains a notice p!aced by the copyright ho!der saying it can be
distributed under the terms of this License. #uch a notice grants a
$or!d'$ide, roya!ty'free !icense, un!imited in duration, to use that
$or, under the conditions stated herein. )he .Document., be!o$,
refers to any such manua! or $or,. -ny member of the pub!ic is a
!icensee, and is addressed as .you.. >ou accept the !icense if you
copy, modify or distribute the $or, in a $ay re/uiring permission
under copyright !a$.
- .Codified Version. of the Document means any $or, containing the
Document or a portion of it, either copied "erbatim, or $ith
modifications and/or trans!ated into another !anguage.
- .#econdary #ection. is a named appendi* or a front'matter section of
the Document that dea!s e*c!usi"e!y $ith the re!ationship of the
pub!ishers or authors of the Document to the Document7s o"era!!
sub<ect Nor to re!ated mattersO and contains nothing that cou!d fa!!
direct!y $ithin that o"era!! sub<ect. N)hus, if the Document is in
part a te*tboo, of mathematics, a #econdary #ection may not e*p!ain
any mathematics.O )he re!ationship cou!d be a matter of historica!
connection $ith the sub<ect or $ith re!ated matters, or of !ega!,
commercia!, phi!osophica!, ethica! or po!itica! position regarding
)he .&n"ariant #ections. are certain #econdary #ections $hose tit!es
are designated, as being those of &n"ariant #ections, in the notice
that says that the Document is re!eased under this License. &f a
section does not fit the abo"e definition of #econdary then it is not
a!!o$ed to be designated as &n"ariant. )he Document may contain Mero
&n"ariant #ections. &f the Document does not identify any &n"ariant
#ections then there are none.
)he .(o"er )e*ts. are certain short passages of te*t that are !isted,
as Front'(o"er )e*ts or +ac,'(o"er )e*ts, in the notice that says that
the Document is re!eased under this License. - Front'(o"er )e*t may
be at most J $ords, and a +ac,'(o"er )e*t may be at most 4J $ords.
- .)ransparent. copy of the Document means a machine'readab!e copy,
represented in a format $hose specification is a"ai!ab!e to the
genera! pub!ic, that is suitab!e for re"ising the document
straightfor$ard!y $ith generic te*t editors or Nfor images composed of
pi*e!sO generic paint programs or Nfor dra$ingsO some $ide!y a"ai!ab!e
dra$ing editor, and that is suitab!e for input to te*t formatters or
for automatic trans!ation to a "ariety of formats suitab!e for input
to te*t formatters. - copy made in an other$ise )ransparent fi!e
format $hose mar,up, or absence of mar,up, has been arranged to th$art
or discourage subse/uent modification by readers is not )ransparent.
-n image format is not )ransparent if used for any substantia! amount
of te*t. - copy that is not .)ransparent. is ca!!ed .0pa/ue..
;*amp!es of suitab!e formats for )ransparent copies inc!ude p!ain
-#(&& $ithout mar,up, )e*info input format, La)e? input format, #GCL
or ?CL using a pub!ic!y a"ai!ab!e D)D, and standard'conforming simp!e
E)CL, Post#cript or PDF designed for human modification. ;*amp!es of
transparent image formats inc!ude PNG, ?(F and 9PG. 0pa/ue formats
inc!ude proprietary formats that can be read and edited on!y by
proprietary $ord processors, #GCL or ?CL for $hich the D)D and/or
processing too!s are not genera!!y a"ai!ab!e, and the
machine'generated E)CL, Post#cript or PDF produced by some $ord
processors for output purposes on!y.
)he .)it!e Page. means, for a printed boo,, the tit!e page itse!f,
p!us such fo!!o$ing pages as are needed to ho!d, !egib!y, the materia!
this License re/uires to appear in the tit!e page. For $or,s in
formats $hich do not ha"e any tit!e page as such, .)it!e Page. means
the te*t near the most prominent appearance of the $or,7s tit!e,
preceding the beginning of the body of the te*t.
)he .pub!isher. means any person or entity that distributes copies of
the Document to the pub!ic.
- section .;ntit!ed ?>`. means a named subunit of the Document $hose
tit!e either is precise!y ?>` or contains ?>` in parentheses fo!!o$ing
te*t that trans!ates ?>` in another !anguage. NEere ?>` stands for a
specific section name mentioned be!o$, such as .-c,no$!edgements.,
.Dedications., .;ndorsements., or .Eistory..O )o .Preser"e the )it!e.
of such a section $hen you modify the Document means that it remains a
section .;ntit!ed ?>`. according to this definition.
)he Document may inc!ude :arranty Disc!aimers ne*t to the notice $hich
states that this License app!ies to the Document. )hese :arranty
Disc!aimers are considered to be inc!uded by reference in this
License, but on!y as regards disc!aiming $arrantiesB any other
imp!ication that these :arranty Disc!aimers may ha"e is "oid and has
no effect on the meaning of this License.
4. V;@+-)&C (0P>&NG
>ou may copy and distribute the Document in any medium, either
commercia!!y or noncommercia!!y, pro"ided that this License, the
copyright notices, and the !icense notice saying this License app!ies
to the Document are reproduced in a!! copies, and that you add no
other conditions $hatsoe"er to those of this License. >ou may not use
technica! measures to obstruct or contro! the reading or further
copying of the copies you ma,e or distribute. Eo$e"er, you may accept
compensation in e*change for copies. &f you distribute a !arge enough
number of copies you must a!so fo!!o$ the conditions in section .
>ou may a!so !end copies, under the same conditions stated abo"e, and
you may pub!ic!y disp!ay copies.
. (0P>&NG &N aU-N)&)>
&f you pub!ish printed copies Nor copies in media that common!y ha"e
printed co"ersO of the Document, numbering more than 155, and the
Document7s !icense notice re/uires (o"er )e*ts, you must enc!ose the
copies in co"ers that carry, c!ear!y and !egib!y, a!! these (o"er
)e*tsB Front'(o"er )e*ts on the front co"er, and +ac,'(o"er )e*ts on
the bac, co"er. +oth co"ers must a!so c!ear!y and !egib!y identify
you as the pub!isher of these copies. )he front co"er must present
the fu!! tit!e $ith a!! $ords of the tit!e e/ua!!y prominent and
"isib!e. >ou may add other materia! on the co"ers in addition.
(opying $ith changes !imited to the co"ers, as !ong as they preser"e
the tit!e of the Document and satisfy these conditions, can be treated
as "erbatim copying in other respects.
&f the re/uired te*ts for either co"er are too "o!uminous to fit
!egib!y, you shou!d put the first ones !isted Nas many as fit
reasonab!yO on the actua! co"er, and continue the rest onto ad<acent
&f you pub!ish or distribute 0pa/ue copies of the Document numbering
more than 155, you must either inc!ude a machine'readab!e )ransparent
copy a!ong $ith each 0pa/ue copy, or state in or $ith each 0pa/ue copy
a computer'net$or, !ocation from $hich the genera! net$or,'using
pub!ic has access to do$n!oad using pub!ic'standard net$or, protoco!s
a comp!ete )ransparent copy of the Document, free of added materia!.
&f you use the !atter option, you must ta,e reasonab!y prudent steps,
$hen you begin distribution of 0pa/ue copies in /uantity, to ensure
that this )ransparent copy $i!! remain thus accessib!e at the stated
!ocation unti! at !east one year after the !ast time you distribute an
0pa/ue copy Ndirect!y or through your agents or retai!ersO of that
edition to the pub!ic.
&t is re/uested, but not re/uired, that you contact the authors of the
Document $e!! before redistributing any !arge number of copies, to
gi"e them a chance to pro"ide you $ith an updated "ersion of the
I. C0D&F&(-)&0N#
>ou may copy and distribute a Codified Version of the Document under
the conditions of sections 4 and abo"e, pro"ided that you re!ease
the Codified Version under precise!y this License, $ith the Codified
Version fi!!ing the ro!e of the Document, thus !icensing distribution
and modification of the Codified Version to $hoe"er possesses a copy
of it. &n addition, you must do these things in the Codified VersionB
-. Use in the )it!e Page Nand on the co"ers, if anyO a tit!e distinct
from that of the Document, and from those of pre"ious "ersions
N$hich shou!d, if there $ere any, be !isted in the Eistory section
of the DocumentO. >ou may use the same tit!e as a pre"ious "ersion
if the origina! pub!isher of that "ersion gi"es permission.
+. List on the )it!e Page, as authors, one or more persons or entities
responsib!e for authorship of the modifications in the Codified
Version, together $ith at !east fi"e of the principa! authors of the
Document Na!! of its principa! authors, if it has fe$er than fi"eO,
un!ess they re!ease you from this re/uirement.
(. #tate on the )it!e page the name of the pub!isher of the
Codified Version, as the pub!isher.
D. Preser"e a!! the copyright notices of the Document.
;. -dd an appropriate copyright notice for your modifications
ad<acent to the other copyright notices.
F. &nc!ude, immediate!y after the copyright notices, a !icense notice
gi"ing the pub!ic permission to use the Codified Version under the
terms of this License, in the form sho$n in the -ddendum be!o$.
G. Preser"e in that !icense notice the fu!! !ists of &n"ariant #ections
and re/uired (o"er )e*ts gi"en in the Document7s !icense notice.
E. &nc!ude an una!tered copy of this License.
&. Preser"e the section ;ntit!ed .Eistory., Preser"e its )it!e, and add
to it an item stating at !east the tit!e, year, ne$ authors, and
pub!isher of the Codified Version as gi"en on the )it!e Page. &f
there is no section ;ntit!ed .Eistory. in the Document, create one
stating the tit!e, year, authors, and pub!isher of the Document as
gi"en on its )it!e Page, then add an item describing the Codified
Version as stated in the pre"ious sentence.
9. Preser"e the net$or, !ocation, if any, gi"en in the Document for
pub!ic access to a )ransparent copy of the Document, and !i,e$ise
the net$or, !ocations gi"en in the Document for pre"ious "ersions
it $as based on. )hese may be p!aced in the .Eistory. section.
>ou may omit a net$or, !ocation for a $or, that $as pub!ished at
!east four years before the Document itse!f, or if the origina!
pub!isher of the "ersion it refers to gi"es permission.
^. For any section ;ntit!ed .-c,no$!edgements. or .Dedications.,
Preser"e the )it!e of the section, and preser"e in the section a!!
the substance and tone of each of the contributor ac,no$!edgements
and/or dedications gi"en therein.
L. Preser"e a!! the &n"ariant #ections of the Document,
una!tered in their te*t and in their tit!es. #ection numbers
or the e/ui"a!ent are not considered part of the section tit!es.
C. De!ete any section ;ntit!ed .;ndorsements.. #uch a section
may not be inc!uded in the Codified Version.
N. Do not retit!e any e*isting section to be ;ntit!ed .;ndorsements.
or to conf!ict in tit!e $ith any &n"ariant #ection.
0. Preser"e any :arranty Disc!aimers.
&f the Codified Version inc!udes ne$ front'matter sections or
appendices that /ua!ify as #econdary #ections and contain no materia!
copied from the Document, you may at your option designate some or a!!
of these sections as in"ariant. )o do this, add their tit!es to the
!ist of &n"ariant #ections in the Codified Version7s !icense notice.
)hese tit!es must be distinct from any other section tit!es.
>ou may add a section ;ntit!ed .;ndorsements., pro"ided it contains
nothing but endorsements of your Codified Version by "arious
parties''for e*amp!e, statements of peer re"ie$ or that the te*t has
been appro"ed by an organiMation as the authoritati"e definition of a
>ou may add a passage of up to fi"e $ords as a Front'(o"er )e*t, and a
passage of up to 4J $ords as a +ac,'(o"er )e*t, to the end of the !ist
of (o"er )e*ts in the Codified Version. 0n!y one passage of
Front'(o"er )e*t and one of +ac,'(o"er )e*t may be added by Nor
through arrangements made byO any one entity. &f the Document a!ready
inc!udes a co"er te*t for the same co"er, pre"ious!y added by you or
by arrangement made by the same entity you are acting on beha!f of,
you may not add another% but you may rep!ace the o!d one, on e*p!icit
permission from the pre"ious pub!isher that added the o!d one.
)he authorNsO and pub!isherNsO of the Document do not by this License
gi"e permission to use their names for pub!icity for or to assert or
imp!y endorsement of any Codified Version.
J. (0C+&N&NG D0(UC;N)#
>ou may combine the Document $ith other documents re!eased under this
License, under the terms defined in section I abo"e for modified
"ersions, pro"ided that you inc!ude in the combination a!! of the
&n"ariant #ections of a!! of the origina! documents, unmodified, and
!ist them a!! as &n"ariant #ections of your combined $or, in its
!icense notice, and that you preser"e a!! their :arranty Disc!aimers.
)he combined $or, need on!y contain one copy of this License, and
mu!tip!e identica! &n"ariant #ections may be rep!aced $ith a sing!e
copy. &f there are mu!tip!e &n"ariant #ections $ith the same name but
different contents, ma,e the tit!e of each such section uni/ue by
adding at the end of it, in parentheses, the name of the origina!
author or pub!isher of that section if ,no$n, or e!se a uni/ue number.
Ca,e the same ad<ustment to the section tit!es in the !ist of
&n"ariant #ections in the !icense notice of the combined $or,.
&n the combination, you must combine any sections ;ntit!ed .Eistory.
in the "arious origina! documents, forming one section ;ntit!ed
.Eistory.% !i,e$ise combine any sections ;ntit!ed .-c,no$!edgements.,
and any sections ;ntit!ed .Dedications.. >ou must de!ete a!! sections
;ntit!ed .;ndorsements..
R. (0LL;()&0N# 0F D0(UC;N)#
>ou may ma,e a co!!ection consisting of the Document and other
documents re!eased under this License, and rep!ace the indi"idua!
copies of this License in the "arious documents $ith a sing!e copy
that is inc!uded in the co!!ection, pro"ided that you fo!!o$ the ru!es
of this License for "erbatim copying of each of the documents in a!!
other respects.
>ou may e*tract a sing!e document from such a co!!ection, and
distribute it indi"idua!!y under this License, pro"ided you insert a
copy of this License into the e*tracted document, and fo!!o$ this
License in a!! other respects regarding "erbatim copying of that
3. -GG@;G-)&0N :&)E &ND;P;ND;N) :0@^#
- compi!ation of the Document or its deri"ati"es $ith other separate
and independent documents or $or,s, in or on a "o!ume of a storage or
distribution medium, is ca!!ed an .aggregate. if the copyright
resu!ting from the compi!ation is not used to !imit the !ega! rights
of the compi!ation7s users beyond $hat the indi"idua! $or,s permit.
:hen the Document is inc!uded in an aggregate, this License does not
app!y to the other $or,s in the aggregate $hich are not themse!"es
deri"ati"e $or,s of the Document.
&f the (o"er )e*t re/uirement of section is app!icab!e to these
copies of the Document, then if the Document is !ess than one ha!f of
the entire aggregate, the Document7s (o"er )e*ts may be p!aced on
co"ers that brac,et the Document $ithin the aggregate, or the
e!ectronic e/ui"a!ent of co"ers if the Document is in e!ectronic form.
0ther$ise they must appear on printed co"ers that brac,et the $ho!e
P. )@-N#L-)&0N
)rans!ation is considered a ,ind of modification, so you may
distribute trans!ations of the Document under the terms of section I.
@ep!acing &n"ariant #ections $ith trans!ations re/uires specia!
permission from their copyright ho!ders, but you may inc!ude
trans!ations of some or a!! &n"ariant #ections in addition to the
origina! "ersions of these &n"ariant #ections. >ou may inc!ude a
trans!ation of this License, and a!! the !icense notices in the
Document, and any :arranty Disc!aimers, pro"ided that you a!so inc!ude
the origina! ;ng!ish "ersion of this License and the origina! "ersions
of those notices and disc!aimers. &n case of a disagreement bet$een
the trans!ation and the origina! "ersion of this License or a notice
or disc!aimer, the origina! "ersion $i!! pre"ai!.
&f a section in the Document is ;ntit!ed .-c,no$!edgements.,
.Dedications., or .Eistory., the re/uirement Nsection IO to Preser"e
its )it!e Nsection 1O $i!! typica!!y re/uire changing the actua!
6. );@C&N-)&0N
>ou may not copy, modify, sub!icense, or distribute the Document
e*cept as e*press!y pro"ided under this License. -ny attempt
other$ise to copy, modify, sub!icense, or distribute it is "oid, and
$i!! automatica!!y terminate your rights under this License.
Eo$e"er, if you cease a!! "io!ation of this License, then your !icense
from a particu!ar copyright ho!der is reinstated NaO pro"isiona!!y,
un!ess and unti! the copyright ho!der e*p!icit!y and fina!!y
terminates your !icense, and NbO permanent!y, if the copyright ho!der
fai!s to notify you of the "io!ation by some reasonab!e means prior to
R5 days after the cessation.
Coreo"er, your !icense from a particu!ar copyright ho!der is
reinstated permanent!y if the copyright ho!der notifies you of the
"io!ation by some reasonab!e means, this is the first time you ha"e
recei"ed notice of "io!ation of this License Nfor any $or,O from that
copyright ho!der, and you cure the "io!ation prior to 5 days after
your receipt of the notice.
)ermination of your rights under this section does not terminate the
!icenses of parties $ho ha"e recei"ed copies or rights from you under
this License. &f your rights ha"e been terminated and not permanent!y
reinstated, receipt of a copy of some or a!! of the same materia! does
not gi"e you any rights to use it.
15. FU)U@; @;V&#&0N# 0F )E&# L&(;N#;
)he Free #oft$are Foundation may pub!ish ne$, re"ised "ersions of the
GNU Free Documentation License from time to time. #uch ne$ "ersions
$i!! be simi!ar in spirit to the present "ersion, but may differ in
detai! to address ne$ prob!ems or concerns. #ee
;ach "ersion of the License is gi"en a distinguishing "ersion number.
&f the Document specifies that a particu!ar numbered "ersion of this
License .or any !ater "ersion. app!ies to it, you ha"e the option of
fo!!o$ing the terms and conditions either of that specified "ersion or
of any !ater "ersion that has been pub!ished Nnot as a draftO by the
Free #oft$are Foundation. &f the Document does not specify a "ersion
number of this License, you may choose any "ersion e"er pub!ished Nnot
as a draftO by the Free #oft$are Foundation. &f the Document
specifies that a pro*y can decide $hich future "ersions of this
License can be used, that pro*y7s pub!ic statement of acceptance of a
"ersion permanent!y authoriMes you to choose that "ersion for the
11. @;L&(;N#&NG
.Cassi"e Cu!tiauthor (o!!aboration #ite. Nor .CC( #ite.O means any
:or!d :ide :eb ser"er that pub!ishes copyrightab!e $or,s and a!so
pro"ides prominent faci!ities for anybody to edit those $or,s. -
pub!ic $i,i that anybody can edit is an e*amp!e of such a ser"er. -
.Cassi"e Cu!tiauthor (o!!aboration. Nor .CC(.O contained in the site
means any set of copyrightab!e $or,s thus pub!ished on the CC( site.
.(('+>'#-. means the (reati"e (ommons -ttribution'#hare -!i,e .5
!icense pub!ished by (reati"e (ommons (orporation, a not'for'profit
corporation $ith a principa! p!ace of business in #an Francisco,
(a!ifornia, as $e!! as future copy!eft "ersions of that !icense
pub!ished by that same organiMation.
.&ncorporate. means to pub!ish or repub!ish a Document, in $ho!e or in
part, as part of another Document.
-n CC( is .e!igib!e for re!icensing. if it is !icensed under this
License, and if a!! $or,s that $ere first pub!ished under this License
some$here other than this CC(, and subse/uent!y incorporated in $ho!e or
in part into the CC(, N1O had no co"er te*ts or in"ariant sections, and
N4O $ere thus incorporated prior to No"ember 1, 455P.
)he operator of an CC( #ite may repub!ish an CC( contained in the site
under (('+>'#- on the same site at any time before -ugust 1, 4556,
pro"ided the CC( is e!igib!e for re!icensing.
-DD;NDUCB Eo$ to use this License for your documents
)o use this License in a document you ha"e $ritten, inc!ude a copy of
the License in the document and put the fo!!o$ing copyright and
!icense notices <ust after the tit!e pageB
(opyright NcO >;-@ >0U@ N-C;.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.
or any !ater "ersion pub!ished by the Free #oft$are Foundation%
$ith no &n"ariant #ections, no Front'(o"er )e*ts, and no +ac,'(o"er )e*ts.
- copy of the !icense is inc!uded in the section entit!ed .GNU
Free Documentation License..
&f you ha"e &n"ariant #ections, Front'(o"er )e*ts and +ac,'(o"er )e*ts,
rep!ace the .$ith...)e*ts.. !ine $ith thisB
$ith the &n"ariant #ections being L&#) )E;&@ )&)L;#, $ith the
Front'(o"er )e*ts being L&#), and $ith the +ac,'(o"er )e*ts being L&#).
&f you ha"e &n"ariant #ections $ithout (o"er )e*ts, or some other
combination of the three, merge those t$o a!ternati"es to suit the
&f your document contains nontri"ia! e*amp!es of program code, $e
recommend re!easing these e*amp!es in para!!e! under your choice of
free soft$are !icense, such as the GNU Genera! Pub!ic License,
to permit their use in free soft$are.
*lphabetical Index
anonymo)s s)bro)tine*****************************************************************************************************************************00
anonymo)s s)bro)tines****************************************************************************************************************************99
arg)ment passing**************************************************************************************************************************************00
base $onversion****************************************************************************************************************************************21
bless . $onstr)$tors***********************************************************************************************************************************95
bless ,6"6,6=C6+ S/,I=G*****************************************************************************************************************52
blessed invo$ant***************************************************************************************************************************************59
Capt)ring and Cl)stering Parenthesis****************************************************************************************************120
Chara$ter Classes***********************************************************************************************************************************121
$ode re'eren$e******************************************************************************************************************************************01
$ode re)se*************************************************************************************************************************************************05
$ommand line***********************************************************************************************************************************************
Command Line rg)ments********************************************************************************************************************104
$omparison **********************************************************************************************************************************************28
$omparison operator*********************************************************************************************************************************28
$omple( data str)$t)res****************************************************************************************************************************82
$onditional operator*********************************************************************************************************************************25
$ontrol 'lo-**********************************************************************************************************************************************89
CP=+ /he Perl :od)le************************************************************************************************************************100
CP=+ /he Geb Site*****************************************************************************************************************************100
Creating :od)les***********************************************************************************************************************************102
1ata Persisten$e***************************************************************************************************************************************89
deep $lone************************************************************************************************************************************************89
dere'eren$ing $ode re'eren$es******************************************************************************************************************01
do)ble ;)ote*********************************************************************************************************************************************12
e;)al to*****************************************************************************************************************************************************28
e(e$)tion timeline************************************************************************************************************************************52
'ile glob**************************************************************************************************************************************************112
"ile Inp)t and >)tp)t*****************************************************************************************************************************110
"ile I>**********************************************************************************************************************************************************
"ile /est********************************************************************************************************************************************************
"ile /ests************************************************************************************************************************************************112
'orea$h************************************************************************************************************************************************29+ 89
garbage $olle$tion*********************************************************************************************************************************94p*
Global :odi'iers************************************************************************************************************************************120
Global :odi'iers !reg)lar e(pressions&*************************************************************************************************120
greater than***********************************************************************************************************************************************28
greater than or e;)al to*****************************************************************************************************************************28
Greedy !:a(imal& K)anti'iers***************************************************************************************************************122
G?I and Perl::/%************************************************************************************************************************************128
here do$)ment******************************************************************************************************************************************18
imaginary n)mbers***********************************************************************************************************************************10
Inheritan$e******************************************************************************************************************************************59+ 99
I=7>C=/ -I :6/4>1**********************************************************************************************************************58
less than****************************************************************************************************************************************************28
less than or e;)al to *********************************************************************************************************************************28
le(i$al s$ope*********************************************************************************************************************************************92
le(i$al variable*****************************************************************************************************************************************92
logi$al operators***************************************************************************************************************************************29
:eta$hara$ters Githin Chara$ter Classes**********************************************************************************************122
method $alls*********************************************************************************************************************************************58
m)ltidimensional array****************************************************************************************************************************88
m)ltiline string*****************************************************************************************************************************************18
named re'erent******************************************************************************************************************************************80
named s)bro)tine*************************************************************************************************************************************99
named s)bro)tines************************************************************************************************************************************99
nat)ral logarithms************************************************************************************************************************************15
not e;)al to***********************************************************************************************************************************************28
>b<e$t 1estr)$tion***********************************************************************************************************************************90
ob<e$t oriented perl***********************************************************************************************************************************52
>b<e$t >riented Perl*********************************************************************************************************************************90
>b<e$t >riented ,evie-***************************************************************************************************************************95
>perating System Commands****************************************************************************************************************114
>verriding :ethods ********************************************************************************************************************************99
pa$%age main********************************************************************************************************************************************91
pa$%age ;)ali'ied variable ***********************************************************************************************************************91
perl mod)les*********************************************************************************************************************************************05
Plain >ld 1o$)mentation***********************************************************************************************************************102
Position ssertions . Position n$hors**************************************************************************************************124
;-*******************************************************************************************************************************************************12+ 18
random n)mbers***************************************************************************************************************************************15
re'*******************************************************************************************************************************************************80+ 54
re'erent***********************************************************************************************************************************************49+ 54
,eg)lar 6(pressions*******************************************************************************************************************************118
a $hara$ter $lass*********************************************************************************************************************************115
Capt)ring and Cl)stering Parenthesis***********************************************************************************************120
Chara$ter Classes******************************************************************************************************************************121
1e'ining a Pattern******************************************************************************************************************************110
Global :odi'iers*******************************************************************************************************************************120
Greedy !:a(imal& K)anti'iers**********************************************************************************************************122
Position ssertions . Position n$hors*********************************************************************************************124
Short$)t Chara$ter Classes****************************************************************************************************************122
/hri'ty !:inimal& K)anti'iers***********************************************************************************************************122
7ariable Interpolation************************************************************************************************************************119
Gild$ard 6(ample*****************************************************************************************************************************110
B1+ B2+ B2*******************************************************************************************************************************************120
s$alar**************************************************************************************************************************************************11+ 22
Short$)t Chara$ter Classes*********************************************************************************************************************122
single ;)ote**********************************************************************************************************************************************12
spa$eship operator************************************************************************************************************************************28
do)ble ;)ote****************************************************************************************************************************************12
single ;)ote******************************************************************************************************************************************12
arg)ment passing*********************************************************************************************************************************00
s)bro)tine $los)res***********************************************************************************************************************************99
s)bro)tine ret)rn val)e*****************************************************************************************************************************02
ternary operator****************************************************************************************************************************************25
/hri'ty !:inimal& K)anti'iers****************************************************************************************************************122
trinary operator*****************************************************************************************************************************************25
)se base :>1?L6=:6**********************************************************************************************************************50
)se lib*******************************************************************************************************************************************************50
)se :od)le***********************************************************************************************************************************************95
)se :>1?L6=:6******************************************************************************************************************************09
B1+ B2+ B2************************************************************************************************************************************************120
The End.

Table of Contents
1 The Impatient Introduction to Perl..........................................................................................................7 1.1 The history of perl in 100 words or less..........................................................................................7 1.2 Basic Formatting for this Document...............................................................................................7 1.3 Do You Have Perl Installed.............................................................................................................8 1.4 Your First Perl Script, EVER..........................................................................................................9 1.5 Default Script Header......................................................................................................................9 1.6 Free Reference Material................................................................................................................10 1.7 Cheap Reference Material.............................................................................................................10 1.8 Acronyms and Terms....................................................................................................................10 2 Storage..................................................................................................................................................11 2.1 Scalars...........................................................................................................................................11 2.1.1 Scalar Strings.........................................................................................................................12 String Literals.................................................................................................................12 Single quotes versus Double quotes..............................................................................13 chomp.............................................................................................................................13 concatenation.................................................................................................................13 repetition........................................................................................................................13 length..............................................................................................................................13 substr..............................................................................................................................13 split.................................................................................................................................14 join.................................................................................................................................14 qw.................................................................................................................................15 Multi-Line Strings, HERE Documents........................................................................15 2.1.2 Scalar Numbers......................................................................................................................16 Numeric Literals............................................................................................................16 Numeric Functions.........................................................................................................16 abs..................................................................................................................................16 int...................................................................................................................................16 trigonometry (sin,cos)....................................................................................................17 exponentiation................................................................................................................17 sqrt..................................................................................................................................17 natural logarithms(exp,log)............................................................................................18 random numbers (rand, srand).......................................................................................18 2.1.3 Converting Between Strings and Numbers.......................................................................19 Stringify.........................................................................................................................19 sprintf.....................................................................................................................19 Numify...........................................................................................................................20 oct...........................................................................................................................21 hex..........................................................................................................................21 Base Conversion Overview....................................................................................21 2.1.4 Undefined and Uninitialized Scalars.....................................................................................22 2.1.5 Booleans................................................................................................................................23 2

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->