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.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".

Cover Art (Front and Back) on the paperback version of Impatient Perl is excluded from
this license. Cover Art is Copyright Greg London 2004, All Rights Reserved.
For latest version of this work go to:
http://www.greglondon.com

1

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
2.1.1.1 String Literals.................................................................................................................12
2.1.1.2 Single quotes versus Double quotes..............................................................................13
2.1.1.3 chomp.............................................................................................................................13
2.1.1.4 concatenation.................................................................................................................13
2.1.1.5 repetition........................................................................................................................13
2.1.1.6 length..............................................................................................................................13
2.1.1.7 substr..............................................................................................................................13
2.1.1.8 split.................................................................................................................................14
2.1.1.9 join.................................................................................................................................14
2.1.1.10 qw.................................................................................................................................15
2.1.1.11 Multi-Line Strings, HERE Documents........................................................................15
2.1.2 Scalar Numbers......................................................................................................................16
2.1.2.1 Numeric Literals............................................................................................................16
2.1.2.2 Numeric Functions.........................................................................................................16
2.1.2.3 abs..................................................................................................................................16
2.1.2.4 int...................................................................................................................................16
2.1.2.5 trigonometry (sin,cos)....................................................................................................17
2.1.2.6 exponentiation................................................................................................................17
2.1.2.7 sqrt..................................................................................................................................17
2.1.2.8 natural logarithms(exp,log)............................................................................................18
2.1.2.9 random numbers (rand, srand).......................................................................................18
2.1.3 Converting Between Strings and Numbers.......................................................................19
2.1.3.1 Stringify.........................................................................................................................19
2.1.3.1.1 sprintf.....................................................................................................................19
2.1.3.2 Numify...........................................................................................................................20
2.1.3.2.1 oct...........................................................................................................................21
2.1.3.2.2 hex..........................................................................................................................21
2.1.3.2.3 Base Conversion Overview....................................................................................21
2.1.4 Undefined and Uninitialized Scalars.....................................................................................22
2.1.5 Booleans................................................................................................................................23
2

2.1.5.1 FALSE...........................................................................................................................24
2.1.5.2 TRUE.............................................................................................................................24
2.1.5.3 Comparators...................................................................................................................25
2.1.5.4 Logical Operators...........................................................................................................26
2.1.5.4.1 Default Values........................................................................................................27
2.1.5.4.2 Flow Control..........................................................................................................27
2.1.5.4.3 Precedence..............................................................................................................27
2.1.5.4.4 Assignment Precedence..........................................................................................27
2.1.5.4.5 Flow Control Precedence.......................................................................................28
2.1.5.4.6 Conditional Operator..............................................................................................28
2.1.6 References..............................................................................................................................29
2.1.7 Filehandles.............................................................................................................................31
2.1.8 Scalar Review........................................................................................................................32
2.2 Arrays............................................................................................................................................32
2.2.1 scalar (@array)......................................................................................................................33
2.2.2 push(@array, LIST)...............................................................................................................34
2.2.3 pop(@array)...........................................................................................................................34
2.2.4 shift(@array)..........................................................................................................................35
2.2.5 unshift( @array, LIST)..........................................................................................................35
2.2.6 foreach (@array)....................................................................................................................36
2.2.7 sort(@array)...........................................................................................................................37
2.2.8 reverse(@array).....................................................................................................................38
2.2.9 splice(@array).......................................................................................................................39
2.2.10 Undefined and Uninitialized Arrays....................................................................................39
2.3 Hashes...........................................................................................................................................39
2.3.1 exists ( $hash{$key} )............................................................................................................41
2.3.2 delete ( $hash{key} ).............................................................................................................42
2.3.3 keys( %hash ).........................................................................................................................42
2.3.4 values( %hash )......................................................................................................................43
2.3.5 each( %hash ).........................................................................................................................43
2.4 List Context...................................................................................................................................47
2.5 References.....................................................................................................................................49
2.5.1 Named Referents...................................................................................................................50
2.5.2 References to Named Referents.............................................................................................50
2.5.3 Dereferencing........................................................................................................................50
2.5.4 Anonymous Referents...........................................................................................................51
2.5.5 Complex Data Structures.......................................................................................................53
2.5.5.1 Autovivification.............................................................................................................54
2.5.5.2 Multidimensional Arrays...............................................................................................55
2.5.5.3 Deep Cloning, Deep Copy.............................................................................................56
2.5.5.4 Data Persistence.............................................................................................................56
2.5.6 Stringification of References.................................................................................................56
2.5.7 The ref() function...................................................................................................................57
3 Control Flow.........................................................................................................................................58
3.1 Labels............................................................................................................................................60
3.2 last LABEL;..................................................................................................................................60
3.3 next LABEL;.................................................................................................................................60
3

.....5 MODULENAME -> import (LISTOFARGS)...............................................4 Lexical Scope...........................................88 12 Procedural Perl....................................................................................................................................................................................72 5.........................................65 4....................68 5 Subroutines...............................................................................................................6 Accessing Arguments inside Subroutines via @_.................................................................................................................................................4 redo LABEL......................3 The PERL5LIB and PERLLIB Environment Variables..............................85 11.........................................................................................80 9...69 5............................................................71 5...............................................................6...........2 use base......74 5.................63 4.............................................78 8 The use Statement..........65 4.........................................................................................3 INVOCANT->isa(BASEPACKAGE)................................................................................... Perl Modules....................................................87 11................94 13.............................................................................8 Calling local() on Package Variables......................................60 4 Packages and Namespaces and Lexical Scoping...86 11.................................................8 Implied Arguments.........................2 The use lib Statement........67 4.............................................................................................................73 5......................................................................................................................................1 The @INC Array............................................................................................................................................................................................................................................................................2 Named Subroutines...................................................................................................................................................................................................................................................................................................................5 Interesting Invocants.............................................61 4................................70 5........................6 The use Execution Timeline......................................6 Garbage Collection.....10 Returning False......................................................................................... Formally..........................................73 5.....................................................................70 5..............................................................69 5........................................................................1 Inheritance.....78 9 The use Statement.....................................62 4.....3 Package Variables inside a Lexical Scope...............................................80 9...............13 Context Sensitive Subroutines with wantarray()..............2 Garbage Collection and Subroutines......................................69 5..............................................................................................................................................................................................................88 11................71 5........................................................................5 Lexical Variables..............................................................................................................1 Reference Count Garbage Collection.................................................................................................................................................82 10 bless()..................62 4...............................12 The caller() function and $wantarray........................................................2 Polymorphism...........................................................................................................................................3..............................................................................................................................................................................................................1 Subroutine Sigil....................63 4.....................................................................................................................7 Package Variables Revisited...........................................................................5 Passing Arguments to/from a Subroutine.....................................................4 INVOCANT->can(METHODNAME)............................6...........................79 9.......................4 Data::Dumper and subroutines.........................2 Declaring Package Variables With our........79 9.............................................................70 5............................................11 Using the caller() Function in Subroutines.........................................................................................81 9.................................................................................83 11 Method Calls........................................................76 7 Code Reuse.........................7 Dereferencing Code References...................80 9......................75 6 Compiling and Interpreting.....................................1 Class............66 4................90 13............1 Package Declaration.....................88 11............94 4 .....................9 Subroutine Return Value.................................................................4 The require Statement................61 4...............................................................................................................................................................................................3 Anonymous Subroutines................................................................................................90 13 Object Oriented Perl..................75 5....................................

...............................................99 14.........................................................................3 bless / constructors...........................................3 read...............98 14............................................2 use Module......................................................................................1 CPAN.....3 Operating System Commands in a GUI..............................................................................................................................................................................................113 19 Operating System Commands...........................105 17...................................................1 The system() function......................7 File Tree Searching................................................................................................................................................................1 The \b Anchor....................................13.............124 20......120 20.........1 Getopt::Declare Sophisticated Example...........................................................................................................................................5 Capturing and Clustering Parenthesis...104 17 Command Line Arguments......................................................2 Capturing parentheses not capturing.......3 Defining a Pattern.........120 20.....5 File Tests...................... $2............6 Character Classes.............117 20.........................................................................................................................................................114 19..........................................................................................................................................................................................................................10..............................................................................6 File Globbing.......................................................4 Methods............................100 15............................................................................................1 open........................................1 Variable Interpolation....................................................................................................................................................................................................1 $1...........1 Metacharacters Within Character Classes...................................................4 Creating Modules for CPAN with h2xs..................................................................117 20.....................................2 The Backtick Operator................................10 Position Assertions / Position Anchors..........114 19.....................................................125 5 ........................................4 Metacharacters......................................................................................................................................................................................................110 18...........10................................................................108 18 File Input and Output.....................................................................................116 20.....................................................................................110 18.......................123 20.......124 20.........5 Inheritance................122 20.............................................................7 Shortcut Character Classes...103 16 The Next Level.................................................................................................................................................................110 18.............................................................4 Object Destruction...............................................................................................................................6...................110 18.....................................................................................................................115 20..........................123 20.................................................................................112 18...................2 Wildcard Example............100 15..........98 14.....................................................................4 write............................................................................................................................................................................107 17..............................................................................................2 The \G Anchor........104 17....................2...................................................... $3................................................................................................................................................................98 14..9 Thrifty (Minimal) Quantifiers...........................98 14...............................................118 20.... The Perl Module.............103 15..1 @ARGV...............................................................................................................................2 CPAN..............................................................95 13......................1 Modules.........................5....................................................................................................................................................................................111 18.......5............................8 Greedy (Maximal) Quantifiers................................................................... etc Capturing parentheses.......121 20..................................99 14..................................................................................................................122 20..................................................................2 Getopt::Declare.................................................6 Overriding Methods and SUPER........112 18.3 SUPER...........................................3 Plain Old Documentation (POD) and perldoc...................97 14 Object Oriented Review...........114 20 Regular Expressions..........................................100 15...................................................................99 15 CPAN.121 20..............................................114 19.....................................................................................................2 close..................................................................................................................... The Web Site....

.................................................................................................................................127 20...136 A quick explanation of the revision history............................................................................... but it's really four lines with hard-coded “\n” at the end of each line....... I fixed a couple of typos and tweaked a sentence or two........................................13 Modifiers for s{}{} Operator..................14 Modifiers for tr{}{} Operator.......... copy and paste the text...............................................................15 The qr{} function..............................................................................................11 Modifiers........................... I lost the original Open Office files for “Impatient Perl”............127 20.............. GUI.....................11............11.................................130 20................130 20......................................129 20.............................................130 20......................................................................................130 20.......20.................................17 Regexp::Common...135 23 GNU Free Documentation License......................130 20.............................................127 20................... It was painfully tedious......................................................... and then manually reformat the document to resemble its original layout.. The January 2010 version attempts to remove all the hard-coded returns in the paragraph text and allow the word processor to determine where to wrap the text.............. One of the problems with that version is that the text had hard-returns coded into it from the cut/paste................................................................................................................................... It might look like there's a four-line paragraph on some page.....131 21 Parsing with Parse::RecDescent........................11.....1 Global Modifiers........ but the revision on 17 February 2009 is that reconstructed version............................................. To recover..................................132 22 Perl........ and Tk....................................................................................................................... Enjoy! Greg London 6 .....16 Common Patterns........................ I had to take the PDF...........12 Modifiers For m{} Operator....3 The x Modifier........2 The m And s Modifiers........... While I was working on that rev..............................................................

A few changes have occurred between then and now.8. not a WORD PROCESSOR to create these files.pm This code will be placed in a file called MyFile. ###filename:MyFile. Larry Wall was working as a sys-admin and found that he needed to do a number of common. This sentence is part of a text section. and probably will not be available for some time.2 Basic Formatting for this Document This document is formatted into text sections. code sections. each file will be labeled.1 The Impatient Introduction to Perl This document is for people who either want to learn perl or are already programming in perl and just do not have the patience to scrounge for information to learn and use perl. so he invented Perl.pl The first line of myscript. and shell sections. Code sections are indented. Text sections will extend to the far left margin and will use a non-monospaced font. yet oddball functions over and over again. If the code section covers multiple files. Text sections contain descriptive text. And he did not like any of the scripting languages that were around at the time. which represents code to type into a script. the code is contained in one file. This is a code section. Perl 6 is on the drawing board as a fundamental rewrite of the language. You will need to use a TEXT EDITOR.pm #!/usr/local/env perl ###filename:myscript. 1.pl This code will be placed in a file called myscript. The current version of Perl has exceeded 5. This document should also find use as a handy desk reference for some of the more common perl related questions.1 The history of perl in 100 words or less In the mid 1980s.pl will be the line with #!/usr/local/env perl 7 . 1. Generally.3 and is a highly recommended upgrade. They also use a monospaced font. and is executed via a shell command. It is not available yet. Version 1 was released circa 1987.

so they are they only things shown. as well as a TON of perl modules for your use. Even if you are not a beginner. Much of this will translate to Mac Perl and Windows Perl. shell sections differ from code sections in that shell sections start with a '>' character which represents a shell prompt. and the output is important. 1. get your sys-admin to install perl for you. If you have an older version or if you have no perl installed at all. shell sections also show the output of a script. It can be typed into a file of any name. As an example. In this example. but the exact translation will be left as an exercise to the reader.8.org CPAN is an acronym for Comprehensive Perl Archive Network. the code is important. The command to run the script is dropped to save space. In simple examples. The CPAN site contains the latest perl for download and installation.> > > > > > > > > > > > > shell sections are indented like code sections shell sections also use monospaced fonts. > Hello World THIS DOCUMENT REFERS TO (LI/U)NIX PERL ONLY.3 Do You Have Perl Installed To find out if you have perl installed and its version: > perl -v You should have at least version 5. shell sections show commands to type on the command line. the code is shown in a code section.3. print "Hello World\n". The name of the file is not important. get your sys-admin to install perl for you. immediately followed by the output from running the script. The command to execute the script is not important either.cpan. if any exists. If you are a beginner. 8 . the code for a simple "Hello World" script is shown here. you can download it for free from http://www.

you will have to run the script by typing: > . 9 . 1. use strict. It uses your PATH environment variable to determine which perl executable to run. EVER Create a file called hello. unless otherwise stated.pl HOORAY! Now go update your resume. use Data::Dumper. > hello. Anything from a # character to the end of the line is a comment.pl extension is simply a standard accepted extension for perl scripts.pl using your favorite text editor." is not in your PATH variable. You can save yourself a little typing if you make the file executable: > chmod +x hello. #!/usr/bin/env perl use warnings.1.5 Default Script Header All the code examples in this document are assumed to have the following script header./hello.pl Hello World If ".pl And then run the script directly. Type in the following: #!/usr/bin/env perl use warnings.) Run the script: > perl hello.4 Your First Perl Script. you can control which version of perl they will run by changing your PATH variable without having to change your script. # comment print "Hello World \n". If you need to have different versions of perl installed on your system. (The #! on the first line is sometimes pronounced "shebang") (The . use strict.pl Hello World This calls perl and passes it the name of the script to execute.

DWIM: Do What I Mean. The acronyms followed. DWIM is just a way of saying the language was designed by some really lazy programmers so that you could be even lazier than they were. Sethi. alright. one where time-torun and memory-usage are issues to be considered). as well as Petty Eclectic Rubbish Lister. The name was invented first. Note that this is "Perl" with a capital "P"." DWIM-iness is an attempt to embed perl with telepathic powers such that it can understand what you wanted to write in your code even though you forgot to actually type it. > > > > perl -h perldoc perldoc -h perldoc perldoc FAQs on CPAN: http://www.Note that Data::Dumper takes some time to load and you wouldn't want to use Data::Dumper on some timing-critical project.com Still more free documentation on the web: http://learn. "vivify" meaning "alive". Tom Christiansen.) AUTOVIVIFY: "auto" meaning "self". If you're writing a “real” script (i. It never does what I want.8 Acronyms and Terms Perl: Originally. well.html Mailing Lists on CPAN: http://list.org/cpan-faq. Once upon a time. I wish that they would sell it. Therefore if you hear reference to some animal book. To bring oneself to life. so they could not be TOO lazy. "Pearl" shortened to "Perl" to gain status as a 4-letter word.org More free documentation on the web: http://www.cpan. (They had to write perl in C. but only what I tell it. the execution speed isn't that high of a priority. Now considered an acronym for Practical Extraction and Report Language.org for more.7 Cheap Reference Material "Programming Perl" by Larry Wall. Well.perldoc. then don't use Data::Dumper by default. it is probably an O'Reilly book. O'Reilly.6 Free Reference Material You can get quick help from the standard perl installation. It is sometimes referred to as the "Camel Book" by way of the camel drawing on its cover. only use it if you really need it. Well. 1. unless its the "Dragon Book". and each one has a different animal on its cover. See http://www. But for learning perl with simple scripts. because that refers to a book called "Compilers" by Aho. has printed enough computer books to choke a. camel.org 1.perl. and Ullman. Generally applies to perl variables that can grant themselves into being without an explicit declaration from the 10 . The "perl" with a lower case "p" refers to the executable found somewhere near /usr/local/bin/perl CPAN: Comprehensive Perl Archive Network.e. Highly recommended book to have handy at all times. and Jon Orwant.cpan. The publisher. the standard mantra for computer inflexibility was this: "I really hate this darn machine.cpan. 1.

Arrays and Hashes use Scalars to build more complex data types. $initial = 'g'. except that fubar somehow got mangled into foobar. References. The most basic storage type is a Scalar. 2. Perl is smart enough to know which type you are putting into a scalar and handle it. "Autovivify" is a verb. and perl is often awash in variables named "foo" and "bar". Part of perl's DWIM-ness. Arrays. $pi = 3. Foo Fighters: A phrase used around the time of WWII by radar operators to describe a signal that could not be explained. Sometimes. autovivification wins. and Hashes. This has nothing to do with perl either. The noun form is "autovivification".programmer. $ref_to_name = \$name # # # # # The “my” keyword declares a lexical variable. Numbers (integers and floats). If you use a $foo variable in your code.1415. Later became known as a UFO. An acronym for Fouled Up Beyond All Recognition and similar interpretations. If you don't know what that means. when "do what I mean" meets autovivification in perl. This has nothing to do with perl. in section 4 11 . a Haiku: Do What I Mean and Autovivification sometimes unwanted TMTOWTDI: There is More Than One Way To Do It. Sometimes.1 Scalars Scalars are preceded with a dollar sign sigil. $name = 'John Doe'. And now. Fubar: Another WWII phrase used to indicate that a mission had gone seriously awry or that a piece of equipment was inoperative. Specifically. Rather than have perl decide which solution is best. and Filehandles. 2 Storage Perl has three basic storage types: Scalars. This allows a programmer to select the tool that will let him get his job done. Scalars can store Strings. except that "foo" is a common variable name used in perl. it gives you all the tools and lets you choose. autovivification is not what you meant your code to do. my my my my my $diameter = 42. sigil : A symbol. In Perl a sigil refers to the symbol in front of a variable. you deserve to maintain it. it gives a perl newbie just enough rope to hang himself. especially if the programmer wishes to hide the fact that he did not understand his code well enough to come up with better names. don't worry about it. An acknowledgment that any programming problem has more than one solution. and for some reason. A "$" is a stylized "S". it will be explained later.

> hello. This is called autovivication. 2.1. This undef value will stringify to "" or numify to 0. mud You can also create a list of string literals using the qw() function. my $greeting = "hello.1 String Literals String literals must be in single or double quotes or you will get an error." and without declaring a variable with a "my".$last)=qw( John Doe ). # numified to 0. (Stringification and Numification are covered later. perl just handles it for you automatically. my ($first. initialize it to zero.1. There is no reason that warnings and strictness should not be turned on in your scripts. my $circumference = $pie * $diameter.1. You do not have to declare the length of the string. and assume that is what you meant to do. $pie doesn't exist. > first is 'John' > last is 'Doe' 12 . therefore $circumference is zero. print hello. However. Autovivified to undef. print $greeting. using a variable causes perl to create one and initialize it to undef. Error: Unquoted string "hello" may clash with reserved word You can use single quotes or double quotes to set off a string literal: my $name = 'mud'. perl will autovivify a new variable called "pie". $name\n". use strict. in certain situations.) Autovivify : to bring oneself to life. print "last is '$last'\n". depending how the undefined variable is used. print "first is '$first'\n". autovivication is handy. autovivification can be an unholy monster. 2.1 Scalar Strings Scalars can store strings. # oops. Without use warnings.Without "use strict. In some situations.

If there are no newlines.2 Single quotes versus Double quotes Single quoted strings are a "what you see is what you get" kind of thing.." my $fullname = 'mud' .5 repetition Repeat a string with the "x" operator.2. LENGTH). # $line is eighty hypens 2. The chomp function removes one new line from the end of the string even if there are multiple newlines at the end. Complex variables. my $len = length($line). The return value of chomp is what was chomped (seldom used). 2.1. 2. will not be interpolated properly in double quotes. My $string = "hello world\n".1.1.1. > hello $name Double quotes means that you get SOME variable interpolation during string evaluation. print "hello $name \n".7 substr substr ( STRING_EXPRESSION.1.4 concatenation String concatenation uses the period character ". "bath".1. my $name = 'mud'.1.3 chomp You may get rid of a newline character at the end of a string by chomp-ing the string.. warn "string is '$string' \n" > string is 'hello world' .1. print 'hello $name'. OFFSET.1.6 length Find out how many characters are in a string with length(). 13 . chomp($string). my $line = '-' x 80.1. such as a hash lookup. 2.1.1. chomp leaves the string alone. > hello mud Note: a double-quoted "\n" is a new-line character. my $name = 'mud'. # $len is 80 2.

'peaches'). Use the split function to break a string expression into components when the components are separated by a common substring pattern. and mutilate strings using substr(). Use join to stitch a list of strings into a single string.1. rather than using a constant literal in the example above. tab separated data in a single string can be split into separate strings.). 9.1. 'bananas'. STRING_EXPRESSION. > string is 'the rain beyond spain' .1. The substr function can also be assigned to.. You can quickly get a chunk of LENGTH characters starting at OFFSET from the beginning or end of the string (negative offsets go from the end). However.. my ($first. The substr function then returns the chunk.. > string is 'apples and bananas and peaches'. warn "string is '$string'". 14 . replacing the chunk as well. STRING2. You need a string contained in a variable that can be modified. my $tab_sep_data = "John\tDoe\tmale\t42". warn "string is '$string'". 2) = 'beyond'. .\s* comma-separated data 2. 2. my $string = 'the rain in spain'. For example.9 join join('SEPARATOR STRING'.Spin.1.. 2).LIMIT). The substr function gives you fast access to get and modify chunks of a string. $tab_sep_data). which is complicated enough to get its own chapter.$age) = split(/\t/. my $chunk = substr('the rain in spain'...$gender. STRING1. The /PATTERN/ in split() is a Regular Expression. my $string = join(" and ".. warn "chunk is '$chunk'". 9.8 split split(/PATTERN/. You can break a string into individual characters by calling split with an empty string pattern "". some common regular expression PATTERNS for split are: \t tab-separated data \s+ whitespace-separated data \s*.. 'apples'. > chunk is 'in' . substr($string. fold.$last.

1.. 15 . 2.. warn "string is '$string'".11 Multi-Line Strings. The '<<' indicates a HERE document.1. My $string = <<”ENDOFDOCUMENT”.2. Enclosing the label in single quotes means that no string interpolation occurs. Do What I Mean and Autovivification sometimes unwanted ENDOFDOCUMENT warn "string is '$string'”.1. qw(apples bananas peaches)). > string is 'Do What I Mean and > Autovivification > sometimes unwanted' at .1..10 qw The qw() function takes a list of barewords and quotes them for you. followed by the name of the label indicating the end of the here document. Enclosing the label in double quotes means that perl variables in the document will get interpolated as strings. Perl then reads the lines after the '<<' as string literal content until it sees the end of string label positioned at the beginning of a line. HERE Documents Perl allows you to place a multi-line string in your code by using what it calls a "here document”.. my $string = join(" and ". > string is 'apples and bananas and peaches'.

4). # binary 2.2. my my my my my $solar_temp_c = 1. not 10! false advertising! my $y_pos = -5. as well as decimal.1. # scalar => integer my $temperature = 98.5e7. my $var1 = abs(-3. If you specify something that is obviously an integer.2 Numeric Functions 2. octal. my $days_in_week = 7.0. Binary numbers begin with "0b" hexadecimal numbers begin with "0x" Octal number begin with a "0" All other numeric literals are assumed to be decimal. # var1 is 3. and scientific notation. # octal $high_address = 0xfa94. Truncating means that positive numbers always get smaller and negative numbers always get bigger. Either way.2 Scalar Numbers Perl generally uses floats internally to store numbers.3 abs Use abs to get the absolute value of a number.9.6. including integer.2. # hexadecimal $low_address = 0b100101. # Fahrenheit $base_address = 01234567. my $dollars = int ($price).9).4 int Use "int" to convert a floating point number to an integer. floating point. # centigrade $solar_temp_f = 27_000_000. my $price = 9.2. my $y_int = int($y_pos).95.1. which means you do NOT get rounding.1 Numeric Literals Perl allows several different formats for numeric literals.2.1.4 my $var2 = abs(5. # scalar => float 2. # dollars is 9.1. you simply use it as a scalar. # var2 is 5.2.9 2.1. it will use an integer. Note that this truncates everything after the decimal point. and hexadecimal. # y_int is -5 (-5 is "bigger" than -5.9) 16 .

# 7 my $cube_root_of_125 = 125 ** (1/3). # 45 deg $radians = $angle * ( 3. you will need to write a bit of code.2.851 OOPS! If you need inverse sine. $price). my $dollars = sprintf("%.cos) The sin() and cos() functions return the sine and cosine of a value given in RADIANS.7 sqrt Use sqrt to take the square root of a positive number. # 3 Standard perl cannot handle imaginary numbers. If you have a value in DEGREES.1.2.1. # 0. # 5 my $fourth_root_of_81 = 81 ** (1/4).0f". # . Use the Math::Complex module on CPAN. or tangent then use the Math::Trig module on CPAN. my my my my $angle = 45. multiply it by (pi/180) first. #125 my $three_to_the_fourth = 3 ** 4.2. # 11. # 0.785 rad $sine_rad = sin($radians).95. 2.707 Correct! $sine_deg = sin($angle). # 81 Use fractional powers to take a root of a number: my $square_root_of_49 = 49 ** (1/2).5 trigonometry (sin.0905 17 .If you want to round a float to the nearest integer.14 / 180 ). my $seven_squared = 7 ** 2. # 49 my $five_cubed = 5 ** 3. # dollars is 10 2. 2.1.6 exponentiation Use the "**" operator to raise a number to some power. One way to accomplish it is to use sprintf: my $price = 9. inverse cosine. my $square_root_of_123 = sqrt(123).

You can pass in a fixed value to guarantee the values returned by rand will always follow the same sequence (and therefore are predictable).2.9 random numbers (rand. You should only need to seed the PRNG once.7183 ** (1/1.7183 my $big_num= exp(42). then use this subroutine: sub log_x_base_b {return log($_[0])/log($_[1]).8 natural logarithms(exp.004. my $inv_exp = log($big_num). which is to say. 18 . # inv_exp = 2.e.7183 ** 42 = 1.e. # answer = 4. srand) The rand function is a pseudorandom number generator (PRNG).2. To get e.log) The exp function returns e to the power of the value given. Natural logarithms simply use the inverse of the value (i. # 2.10).1 Note that inverse natural logs can be done with exponentiation. The exp function is straightforward exponentiation: # big_num = 2.7e18) = 42 my $inv_exp = $value_of_e ** (1/$big_num). you should not need to call it at all.} # want the log base 10 of 12345 # i. because perl will call srand at startup. rand returns a number that satisfies ( 0 <= return <= input ) If no value is passed in. to what power do we need to raise the # number 10 to get the value of 12345? my $answer = log_x_base_b(12345. call exp(1). If you have a version of perl greater than or equal to 5.7183 ** 42 = 1. my $value_of_e = exp(1).1.718281828). you just need to know the value of the magic number e (~ 2. srand will seed the PRNG with something from the system that will give it decent randomness. 1/value) with exponentiation.7e18 The log function returns the inverse exp() function.2. 2. If a value is passed in.1.7e18 my $big_num = $value_of_e ** 42. If no value is passed in. log returns the number to which you would have to raise e to get the value passed in. # inv_exp = 42 If you want another base. # 2. rand returns a number in the range ( 0 <= return < 1 ) The srand function will seed the PRNG with the value passed in.

1415. Even though $mass is stored internally as a floating point number and $volume is stored internally as an integer.14' .3. my $str = sprintf("%06.1. 19 . sprintf ( FORMAT_STRING. my $volume = 4.3.3. LIST_OF_VALUES ).2f". # '7.. > str is '003. my $mass = 7. # 7.1. 2..3.= ''. the code did not have to explicitly convert these numbers to string format before printing them out. > mass is '7.. simply concatenate a null string onto the end of the value. Perl is not one of these languages.3 Converting Between Strings and Numbers Many languages require the programmer to explicitly convert numbers to strings before printing them out and to convert strings to numbers before performing arithmetic on them. There are two basic conversions that can occur: stringification and numification.. > volume is '4' . warn "mass is '$mass'\n". If you want to force stringification..1 Stringify Stringify: Converting something other than a string to a string form. my $mass = 7.1.1 sprintf Use sprintf to control exactly how perl will convert a number into string format. use sprintf.$pi). warn "volume is '$volume'\n". warn "str is '$str'". Perl will attempt to convert the numbers into the appropriate string representation.3' . Perl will automatically convert a number (integer or floating point) to a string format before printing it out. For example: my $pi = 3. If you do not want the default format.3 my $string_mass = $mass .2.. Perl will attempt to apply Do What I Mean to your code and just Do The Right Thing.1.3' 2.

or decimal formated string. Sometimes you have string information that actually represents a number. # '19.95" which must be converted to a float before perl can perform any arithmetic on it. including decimal point .3. You can force numification of a value by adding integer zero to it. a user might enter the string "19. use the following FORMAT_STRINGS: hexadecimal "%lx" The letter 'l' (L) octal "%lo" indicates the input is binary "%lb" an integer.Decoding the above format string: % => format 0 => fill leading spaces with zero 6 => total length. binary. then use oct() or hex() 20 . possibly decimal integer "%ld" a Long integer.2 => put two places after the decimal point f => floating point notation To convert a number to a hexadecimal. For example.95' my $price = $user_input+0.95 If the string is NOT in base ten format. octal. # 19.2 Numify Numify: Converting something other than a number to a numeric form.1. my $user_input = '19.95'. decimal float "%f" scientific "%e" 2.

1. binary formatted strings must start with "0b" hexadecimal formatted strings must start with "0x" All other numbers are assumed to be octal strings. my $bin = sprintf("%lb". use this: # 08 assumes width is 8 characters my $p_hex = sprintf("%08lx".3 Base Conversion Overview Given a decimal number: my $decimal=12. Note: even though the string might not start with a zero (as required by octal literals). Then. $decimal). my $oct = sprintf("%lo".2. $decimal). else assume it's decimal. The hex() function is like oct() except that hex() only handles hex base strings. OR decimal strings. If you want to pad the most significant bits with zeroes and you know the width. 2.2. call oct on it. binary. and it does not require a "0x" prefix.3.2. Convert from decimal to another base using sprintf: my $hex = sprintf("%lx". $decimal). my $p_oct = sprintf("%08lo". This example uses regular expressions and the conditional operator. 2. hexadecimal. if the string starts with zero. To handle a string that could contain octal.2. 21 . my $num = ($str=~m{^0}) ? oct($str) : $str + 0.3. my $p_bin = sprintf("%08lb". you could assume that octal strings must start with "0". This means calling oct() on a decimal number could be a bad thing. oct will assume the string is octal.1. $decimal). $decimal).2 hex The hex() function takes a string in hex format and converts it to integer. hexadecimal.1. or binary format and convert it to an integer.1 oct The oct function can take a string that fits the octal.3. $decimal).

If the scalar is defined.4 Undefined and Uninitialized Scalars All the examples above initialized the scalars to some known value before using them.If you have a string and you want to convert it to decimal. # oct convert_to_decimal('0xff'). but a warning is emitted.1. # dec convert_to_decimal('032'). # hex convert_to_decimal('0b1001011'). the variable is undefined. 255)). convert it to binary using sprintf (don't pad with zeros) and then call length() on it. Since perl automatically performs this conversion no matter what. there is no string or numeric operation that will tell you if the scalar is undefined or not. If you use a scalar that is undefined. With warnings/strict on. # 8 2. the function returns a boolean "true" (1) If the scalar is NOT defined. perl will stringify or numify it based on how you are using the variable. in which case. You can declare a variable but not initialize it. # bin If you want to know how many bits it would take to store a number. the conversion still takes place. warn length(sprintf("%lb". this conversion is silent. An undefined scalar stringifies to an empty string: "" An undefined scalar numifies to zero: 0 Without warnings or strict turned on. } warn warn warn warn convert_to_decimal('42'). the function returns a boolean "false" (""). sub convert_to_decimal { ($_[0]=~m{^0}) ? Oct($_[0]) : $_[0] + 0. use the conditional operator and oct(). Use the defined() function to test whether a scalar is defined or not. 22 .

This will be exactly as if you declared the variable with no initial value. and then treated as a string or number by the above rules. A subroutine returns a scalar or a list depending on the context in which it is called.} $var = undef. if(defined($var)) {print "defined\n". # defined print "test 2 :". The scalar context of an ARRAY is its size. To explicitly return FALSE in a subroutine. An array with one undef value has a scalar() value of 1 and is therefore evaluated as TRUE. any other number is TRUE 3) all references are TRUE 4) undef is FALSE Note that these are SCALARS.5 Booleans Perl does not have a boolean "type" per se.} > test 1 :undefined > test 2 :defined > test 3 :undefined 2. use this: return wantarray() ? () : 0. Instead. perl interprets scalar strings and numbers as "true" or "false" based on some rules: 1)Strings "" and "0" are FALSE. any other string or stringification is TRUE 2) Number 0 is FALSE. assign undef to it. # undef print "test 1 :". Any variable that is not a SCALAR is first evaluated in scalar context. #FALSE 23 .} $var = 42. and you want to return it to its uninitialized state. my $var.} else {print "undefined\n".If you have a scalar with a defined value in it.1. if(defined($var)) {print "defined\n". # undef as if never initialized print "test 3 :". # FALSE This is sufficiently troublesome to type for such a common thing that an empty return statement within a subroutine will do the same thing: return.} else {print "undefined\n". if(defined($var)) {print "defined\n".} else {print "undefined\n".

5. even though you might not have expected them to be false.0' # true string '00' # true string 'false' # true float 3. which is FALSE.1. which means the following scalars are considered TRUE. If you are processing a number as a string and want to evaluate it as a BOOLEAN.1415 # true integer 11 # true string 'yowser' # true If you are doing a lot of work with numbers on a variable. Built in Perl functions that return a boolean will return an integer one (1) for TRUE and an empty string ("") for FALSE.2 TRUE ALL other values are interpreted as TRUE.0'+0) will get numified to 0.1 FALSE The following scalars are interpreted as FALSE: integer 0 # false float 0.0" instead of a float 0.2. string '0.0 # false string '0' # false string '' # false undef # false 2. Note that the string '0. just in case you end up with a string "0. but ('0.0 and get some seriously hard to find bugs. 24 .0' is TRUE. make sure you explicitly NUMIFY it before testing its BOOLEANNESS.1.5. you may wish to force numification on that variable ($var+0) before it gets boolean tested.

If you use a numeric operator to compare two strings.5. However.1. if warnings/strict is not on. And if you wanted the numbers compared numerically but used string comparison. you will get their alphabetical string comparison. perl will attempt to numify the strings and then compare them numerically. assigning the numification of "John" to integer zero. Perl will stringify the numbers and then perform the compare. The numeric comparison operator '<=>' is sometimes called the "spaceship operator". then you will get the wrong result when you compare the strings ("9" lt "100"). specifically an integer 1 for true and a null string "" for false. 25 . perl will emit no warning. gt=+1) cmp <=> equal to Note that if you use a string operator to compare two numbers. or +1.3 Comparators Comparison operators return booleans. Number 9 is less than (<=) number 100. This will occur silently. or greater than. Function String Numeric Function String Numeric equal to eq == not equal to ne != less than lt < greater than gt > less than or equal to le <= greater than or equal to ge >= comparison (lt=-1. Comparing "John" <= "Jacob" will cause perl to convert "John" into a number and fail miserably. Distinct comparison operators exist for comparing strings and for comparing numbers. equal to. it will fail miserably and SILENTLY. eq=0. String "9" is greater than (gt) string "100". The "Comparison" operator ("<=>" and "cmp") return a -1.2. 0. indicating the compared values are less than.

But first. '||'. and 'xor' operators. and '!' operators. NOT functions. 'or'. The higher precedence logical operators are the '&&'. so it is useful to learn how precedence affects their behavior. OR. function operator usage return value AND and $one and $two if ($one is false) $one else $two OR or $one or $two if ($one is true) $one else $two NOT not not $one if ($one is false) true else false XOR xor $one xor $two if ( ($one true and $two false) or ($one false and $two true) ) then return true else false Both sets of operators are very common in perl code.2. 26 .5. some examples of how to use them.4 Logical Operators Perl has two sets of operators to perform logical AND. 'not'. The difference between the two is that one set has a higher precedence than the other set.1. function operator usage return value AND && $one && $two if ($one is false) $one else $two OR || $one || $two if ($one is true) $one else $two NOT ! ! $one if ($one is false) true else false The lower precedence logical operators are the 'and'.

1.2 Flow Control The open() function here will attempt to open $filename for reading and attach $filehandle to it. but the end result is code that is actually quite readable. If open() fails in any way. and we used the one with the precedence we needed. } The '||=' operator is a fancy shorthand.5. $right ||= 2.1. $right )=@_. $filename) or die "cant open".5. because they have a higher precedence than (and are evaluated before) the assignment '='. is exactly the same as this: $left = $left || 1. If the user calls the subroutine with missing arguments.0.4. # default is 1 27 . 2.5. the undefined parameters will instead receive their default values. and FALSE OR'ed with die () means that perl will evaluate the die() function to finish the logical evaluation.4.3 Precedence The reason we used '||' in the first example and 'or' in the second example is because the operators have different precedence.0).2.0 and 2. open (my $filehandle. $left ||= 1.1 Default Values This subroutine has two input parameters ($left and $right) with default values (1. followed by any remaining 'and' and 'or' operators.0. meaning the assignment would occur first. This: $left ||= 1.0. Right: my $default = 0 || 1.4 Assignment Precedence When working with an assignment. 2.5.1. It won't complete because execution will die.4. # deal with $left and $right here.4. it returns FALSE.1. 2. The 'or' and 'and' operators have a precedence that is LOWER than an assignment. sub mysub { my( $left. use '||' and '&&'.0.

NEVER die.5. the conditional operator is perl's ONLY trinary operator. The '||' and '&&' have higher precedence than functions and may execute before the first function call.6 Conditional Operator The conditional operator mimics the conditional testing of an if-else block. the return value is discarded. but it is probably better to get in the habit of using the right operator for the right job. 2. which will ALWAYS evaluate $fh as true.Wrong: my $default = 0 or 1. Right: close $fh or die "Error:could not close". its not a problem. If close() fails.1.4. which will ALWAYS assign $default to the first value and discard the second value. # default is 0 The second (wrong) example is equivalent to this: (my $default = 0) or 1. use 'or' and 'and' operators. The conditional operator has this form: my $RESULT = $BOOLEAN1 ? $VALUE1 : $VALUE2. and the program continues on its merry way.1. The second (wrong) example is equivalent to this: close ($fh || die "Error"). and is also called a trinary operator. so people sometimes call it the trinary or ternary operator when they mean conditional operator. 2. The conditional operator uses three operands. It is even more rarely called the ?: operator. Wrong: close $fh || die "Error: could not close". As it happens.5. As long as perl doesn't add another trinary operator.4. because they have lower precedence than functions and other statements that form the boolean inputs to the 'or' or 'and' operator.5 Flow Control Precedence When using logical operators to perform flow control. 28 . and close $fh. It is always possible to override precedence with parentheses.

Unlike C. 29 .This can be rewritten as an if-else block like this: my $RESULT.1. if($BOOLEAN1) elsif($BOOLEAN2) elsif($BOOLEAN3) elsif($BOOLEAN4) eles { $RESULT = { $RESULT { $RESULT { $RESULT { $RESULT $VALUE5 } = = = = $VALUE1 $VALUE2 $VALUE3 $VALUE4 } } } } 2. For example: my $RESULT = $BOOLEAN1 ? : $BOOLEAN2 ? : $BOOLEAN3 ? : $BOOLEAN4 ? : $VALUE5. effectively allowing you to create a chain of if-elsifelsif-else statements. $age = 42. $name_ref = \$name. $VALUE1 and $VALUE2 can be replaced by any normal perl expression. It is kind of like a pointer in C.6 References A reference points to the variable to which it refers. which says "the data I want is at this address". Create a reference by placing a "\" in front of the variable: my my my my $name = 'John'. You can only create a reference to a variable that is visible from your current scope. $VALUE1 $VALUE2 $VALUE3 $VALUE4 The above example is equivalent to this mouthful: my $RESULT. if($BOOLEAN1) { $RESULT = $VALUE1 } else { $RESULT = $VALUE2 } The conditional operator allows you to declare the variable and perform the assignment all in one short line of code. One interesting expression that you could replace $VALUE2 with is another conditional operator. $age_ref = \$age. you cannot manually alter the address of a perl reference. rather than being limited to a simple scalar value. Note that $BOOLEAN1.

You cannot referencify a string. It also tells you the address of the variable to which we are referring is 0x812e6ec.Perl will stringify a reference so that you can print it and see what it is. such as "SCALAR (0x83938949)" and have perl give you a reference to whatever is at that address... 30 . > age_ref is 'SCALAR(0x812e6ec)' . I. This tells you that $age_ref is a reference to a SCALAR (which we know is called $age). warn "age_ref is '$age_ref'". you cannot give perl a string. Perl is pretty loosy goosey about what it will let you do. but not even perl is so crazy as to give people complete access to the system memory.E.

print $fh "this is simple file writing\n". The scalar $fh in the example above holds the filehandle to "out. File IO gets its own section. warn Dumper \$ref_to_name. print $fh "hello world\n". Data::Dumper will take a reference to ANYTHING and print out the thing to which it refers in a human readable form. but that is a quick intro to scalar filehandles. '>out. References are interesting enough that they get their own section. my $ref_to_name = \$name.txt". This does not seem very impressive with a reference to a scalar: my $name = 'John'. Given a scalar that is undefined (uninitialized). my $ref_to_name = \$name. 31 . Printing to the filehandle actually outputs the string to the file. but I introduce it here to give a complete picture of what scalars can hold.. close($fh). warn $deref_name. But this will be absolutely essential when working with Arrays and Hashes. There is some magic going on there that I have not explained. 2.txt').. open(my $fh.7 Filehandles Scalars can store a filehandle. my $name = 'John'. my $deref_name = $$ref_to_name.1. and store the handle to that file in the scalar. > $VAR1 = \'John'. But I introduce them here so that I can introduce a really cool module that uses references: Data::Dumper. > John . calling open() on that scalar and a string filename will tell perl to open the file specified by the string.You can dereference a reference by putting an extra sigil (of the appropriate type) in front of the reference variable.

The "@" is a stylized "a".2 Arrays Arrays are preceded with an "at" sigil. Stringify: to convert something to a string format Numify: to convert something to a numeric format The following scalars are interpreted as boolean FALSE: integer 0. An array stores a bunch of scalars that are accessed via an integer index. float 0.8 Scalar Review Scalars can store STRINGS. warn $string. When you refer to an entire array. > two . my @numbers = qw ( zero one two three ). NUMBERS (floats and ints).. (Do Not Panic. 32 . undef All other scalar values are interpreted as boolean TRUE.) The first element of an array always starts at ZERO (0).0. the "@" character changes to a "$" and the numeric index is placed in square brackets. my @numbers = qw ( zero one two three ). string "0". and FILEHANDLES. use the "@" sigil.2. string "". my $string = $numbers[2]. 2.1.. Perl arrays are ONE-DIMENSIONAL ONLY. When you index into the array. REFERENCES.

9*11. '*'... my @months. '//'.. # $months[1] > ${\$VAR1->[0]}. # this is same as undef > ${\$VAR1->[0]}. 'daba' ). # undef > 'May' # $months[5] > ].1. which is initialized to 1 Arrays can store ANYTHING that can be stored in a scalar my @junk_drawer = ( 'pliers'. > $VAR1 = [ > undef. Perl autovivifies whatever space it needs.14..The length of an array is not pre-declared. 2. my $quantity = scalar(@phonetic). # $months[0] and $months[2. # the array is filled with undefs # except the last entry. warn "last is '$last'".1 scalar (@array) To get how many elements are in the array. my @colors = qw ( red green blue ).2. warn $quantity. 3. Negative indexes start from the end of the array and work backwards.4] are autovivified # and initialized to undef print Dumper \@months. try running this piece of code: my @mem_hog. $months[1]='January'. # undef > ${\$VAR1->[0]}. $months[5]='May'. If you want to see if you can blow your memory. 33 . 1. use "scalar" my @phonetic = qw ( alpha bravo charlie delta ). > 4 .. $mem_hog[10000000000000000000000]=1.1. # index 0 is undefined > 'January'. my $last=$colors[-1]. 'yaba'. > last is 'blue' .

qw ( eggs bacon cheese )). > 3 ..3 pop(@array) Use pop() to get the last element off of the end of the array (the highest index). 'bob' ]. $VAR1 = [ 'alice'.2. warn "popped = $last_name".When you assign an entire array into a scalar variable. warn $quant.. LIST) Use push() to add elements onto the end of the array (the highest index). 'eggs'.2. This will shorten the array by one. This will increase the length of the array by the number of items added. but calling scalar() is much more clear..2 push(@array. my @groceries = qw ( milk bread ). print Dumper \@groceries. 2. my $last_name = pop(@names). print Dumper \@names. > > > > > popped = charlie . 34 . The return value of pop() is the value popped off of the array. my @names = qw ( alice bob charlie ). 'cheese' ]. 2. 'bacon'.. This is explained later in the "list context" section. push(@groceries. you will get the same thing. > > > > > > > $VAR1 = [ 'milk'. my @phonetic = qw ( alpha bravo charlie ). 'bread'. my $quant = @phonetic.

> > > > > > $VAR1 = [ 'birch'.e. The array will be shorted by one. # 2 'oak' # 3 ].4 shift(@array) Use shift() to remove one element from the beginning/bottom of an array (i. 'foe'. 'birch'). # index 0 'pine'. at index zero).2. This will length the array by the number of elements in LIST. my $start = shift(@curses). warn Dumper \@trees. warn $start. # old index 0. at index ZERO). All elements will be shifted DOWN one index. 'fum' ]. 2. my @trees = qw ( pine maple oak ).2.2. now 1 'maple'. LIST) use unshift() to add elements to the BEGINNING/BOTTOM of an array (i. > > > > > > fee $VAR1 = [ 'fie'. 35 .5 unshift( @array.e. The return value is the value removed from the array. unshift(@trees. my @curses = qw ( fee fie foe fum ). warn Dumper \@curses. All the other elements in the array will be shifted up to make room.

my @numbers = qw (zero one two three). } > > > # # # num is 'zero' num is 'one' num is 'three' note: I deleted 'zero'. next. } > > > > fruit fruit fruit fruit is is is is 'apples' 'oranges' 'lemons' 'pears' DO NOT ADD OR DELETE ELEMENTS TO AN ARRAY BEING PROCESSED IN A FOREACH LOOP. which is still part of array.2.6 foreach (@array) Use foreach to iterate through all the elements of a list. print "num is '$num'\n". The foreach structure supports last.2. Use a simple foreach loop to do something to each element in an array: my @fruits = qw ( apples oranges lemons pears ). and redo statements. foreach my $num (@numbers) { shift(@numbers) if($num eq 'one'). Its formal definition is: LABEL foreach VAR (LIST) BLOCK This is a control flow structure that is covered in more detail in the "control flow" section. foreach my $fruit (@fruits) { print "fruit is '$fruit'\n". BAD!! 36 . but I failed to print out 'two'.

my @sorted_array = sort(@scores). 200. foreach my $num (@integers) { $num+=100. Changes to VAR propagate to changing the array. 76 ]. } print Dumper \@integers. which probably is not what you want. > 'oranges'. print Dumper \@sorted_array . 84048 ]. print Dumper \@sorted_array . # 1's 150. 83948 ). 76. >$VAR1 = [ > 'apples'. > 'pears' > ].2. 27. 13.VAR acts as an alias to the element of the array itself. my @integers = ( 23. my @scores = ( 1000. 142. The return value is the sorted version of the array. > > > > > > > > $VAR1 = [ 1000. 9484. The array passed in is left untouched. my @fruit = qw ( pears apples bananas oranges ). 9384. my @sorted_array = sort(@fruit). 27. 37 . > > > > > > $VAR1 = [ 123. # 1's 200. Sorting a list of numbers will sort them alphabetically as well. # 1's 13. 150 ). 2.7 sort(@array) Use sort() to sort an array alphabetically. > 'bananas'. 242.

13. 200. print Dumper \@sorted_array .76. The first element becomes the last element. This is how you would sort an array numerically.2. print Dumper \@numbers . > 1000 > ]. 76. my @numbers = reverse (1000. > 13. > 76.27. 27. > > > > > > > > $VAR1 = [ 13.The sort() function can also take a code block ( any piece of code between curly braces ) which defines how to perform the sort if given any two elements from the array.150). 1000 ]. $a and $b. 150 ). 200. 150.8 reverse(@array) The reverse() function takes a list and returns an array in reverse order. 27.200. The last element becomes the first element. 13. 76. The code block uses two global variables. my @scores = ( 1000. > $VAR1 = [ > 150. > 27. my @sorted_array = sort {$a<=>$b} (@scores). 2. 38 . > 200. and defines how to compare the two entries.

9 splice(@array) Use splice() to add or remove elements into or out of any index range of an array. The "%" is a stylized "key/value" pair. warn join(" ". and leave you with a completely empty array. > hello out there . my @array = (). then the array is uninitialized. then you do NOT want to assign it undef like you would a scalar. there is. OFFSET .e.) There is no order to the elements in a hash.2. LENGTH . This is equivalent to calling defined() on a scalar variable. 39 . This will clear out any entries. integer 0). 0. If you want to uninitialize an array that contains data. assign an empty list to it. @words). A hash stores a bunch of scalars that are accessed via a string index called a "key" Perl hashes are ONE-DIMENSIONAL ONLY. but you should not use a hash with an assumption about what order the data will come out. # RIGHT 2. splice(@words. my @words = qw ( hello there ).2. 'out'). (Well. Any elements from LIST will be inserted at OFFSET into ARRAY. The elements in ARRAY starting at OFFSET and going for LENGTH indexes will be removed from ARRAY. 1. Therefore you can test to see if an array is initialized by calling scalar() on it. my @array = undef. The first item will be treated as the key. This would fill the array with one element at index zero with a value of undefined.) You can assign any even number of scalars to a hash. # WRONG To clear an array to its original uninitialized state. LIST ). (Do Not Panic.10 Undefined and Uninitialized Arrays An array is initialized as having no entries. If scalar() returns false (i. 2. splice ( ARRAY .2. Perl will extract them in pairs..3 Hashes Hashes are preceded with a percent sign sigil. and the second item will be treated as the value..

my $data = $info{name}. the key is created and given the assigned value./test.. print Dumper \%inventory. warn "peaches is '$peaches'". $inventory{apples}=42. The keys of a hash are not pre-declared. and undef is returned. my %inventory. > > > > > Use of uninitialized value in concatenation peaches is '' at . my %info = qw ( name John age 42 ). > 'apples' => 42. warn $data. > 'pears' => 17 > }. $inventory{bananas}=5. $inventory{pears}=17. If the key does not exist during a FETCH.. 40 . When you look up a key in the hash.pl line 13. my $peaches = $inventory{peaches}. If the key does not exist during an ASSIGNMENT. my %inventory. > John . >$VAR1 = { > 'bananas' => 5. use the "%" sigil. $inventory{apples}=42. my %info = qw ( name John age 42 ). print Dumper \%inventory. the "%" character changes to a "$" and the key is placed in curly braces. $VAR1 = { 'apples' => 42 }.When you refer to an entire hash. the key is NOT created.

we explicitly create the key "Florida". You cannot simply test the value of a key. } } print Dumper \%stateinfo. 'Maine' => {} You must test each level of key individually. > $VAR1 = { > > > > > }. $stateinfo{Florida}->{Abbreviation}='FL'. { 'Abbreviation' => 'FL' } 41 . but this is a "feature" specific to exists() that can lead to very subtle bugs. $stateinfo{Florida}->{Abbreviation}='FL'. } Warning: during multi-key lookup. Note in the following example.2. but we only test for the existence of {Maine}>{StateBird}. since a key might exist but store a value of FALSE my %pets = ( cats=>2. my %stateinfo. dogs=>1 ). 'Florida' => { 'Abbreviation' => 'FL' }. } print Dumper \%stateinfo. all the lower level keys are autovivified. and only the last key has exists() tested on it. and build your way up to the final key lookup if you do not want to autovivify the lower level keys.3. which has the side effect of creating the key {Maine} in the hash. if (exists($stateinfo{Maine}->{StateBird})) { warn "it exists". References are covered later. my %stateinfo. This only happens if you have a hash of hash references.1 exists ( $hash{$key} ) Use exists() to see if a key exists in a hash. unless(exists($pets{fish})) { print "No fish here\n". > $VAR1 = { > 'Florida' => > > > }. if (exists($stateinfo{Maine})) { if (exists($stateinfo{Maine}->{StateBird})) { warn "it exists".

print Dumper \%pets. ). Note in the example below that the order of assignment is different from the order printed out.3 keys( %hash ) Use keys() to return a list of all the keys in a hash.3. cats=>2. then you may wish to use the each() function described below. foreach my $pet (keys(%pets)) { print "pet is '$pet'\n". 'dogs' => 1 2. 42 . my %pets = ( fish=>3. The only way to remove a key/value pair from a hash is with delete().2 delete ( $hash{key} ) Use delete to delete a key/value pair from a hash. and should not be something your program depends upon. $pets{cats}=undef. dogs=>1. cats=>2.3. The order of the keys will be based on the internal hashing algorithm used. ). assigning undef to it will keep the key in the hash and will only assign the value to undef. dogs=>1. 'cats' => undef. my %pets = ( fish=>3. delete($pets{fish}).2. } > pet is 'cats' > pet is 'dogs' > pet is 'fish' If the hash is very large. > $VAR1 = { > > > }. Once a key is created in a hash.

qty='3' 43 . The order of the values will match the order of the keys return in keys(). qty='$qty'\n". print Dumper \@pet_keys. qty='1' > pet='fish'. 'dogs'. my %pets = ( fish=>3.3. qty='2' > pet='dogs'.$qty)=each(%pets)) { print "pet='$pet'. cats=>2. my %pets = ( fish=>3. ).4 values( %hash ) Use values() to return a list of all the values in a hash. one at a time. cats=>2. > $VAR1 = [ > > > > ]. print Dumper \@pet_vals. 3 If the hash is very large. my @pet_keys = keys(%pets). dogs=>1. 1. 'fish' 2. my @pet_vals = values(%pets). then you may wish to use the each() function described below. ). > $VAR1 = [ > > > > ]. 2. dogs=>1.3.5 each( %hash ) Use each() to iterate through each key/value pair in a hash.2. while(my($pet. } > pet='cats'. 'cats'.

You can delete keys while iterating a hash with each(). After the last key/value pair is returned. dogs=>1. # dogs 44 . which is boolean false. # end of hash one_time. } } one_time. # dogs keys(%pets). keys(%hash). my %pets = ( fish=>3. # cats one_time. the next call to each() will return an empty list. # dogs one_time. qty='$qty'\n". } else { print "end of hash\n". ). The subroutine is called multiple times without using a while() loop.$qty)=each(%pets). Calling keys() on the hash will reset the iterator. sub one_time { my($pet. # if key is not defined. # reset the hash iterator one_time. # then each() must have hit end of hash if(defined($pet)) { print "pet='$pet'. cats=>2. # fish one_time. This is how the while loop is able to loop through each key/value and then exit when done. The each() function does not have to be used inside a while loop. Do not add keys while iterating a hash with each(). This example uses a subroutine to call each() once and print out the result. # cats one_time. The list returned by keys() can be discarded.Every call to each() returns the next key/value pair in the hash. This iterator is used by perl to remember where it is in the hash for the next call to each(). Every hash has one "each iterator" attached to it. # cats one_time.

namely at the end of the list."than $cmp_pet\n". qty='2' qty='1' qty='2' qty='1' qty='3' qty='2' qty='1' There is only one iterator variable connected with each hash. The inside loop continues..$cmp_qty)=each(%pets)) { if($orig_qty>$cmp_qty) { print "there are more $orig_pet " . 45 . The outside loop calls each() which continues where the inside loop left off. are are are are are are are are more less more less more less more less cats cats cats cats cats cats cats cats than than than than than than than than dogs fish dogs fish dogs fish dogs fish The outside loop calls each() and gets "cats". cats=>2. my %pets = ( fish=>3. and returns "cats". while(my($orig_pet. The example below goes through the %pets hash and attempts to compare the quantity of different pets and print out their comparison. calls each() again. pet='fish'.. } else { print "there are less $orig_pet " . The code then enters the inside loop.$orig_qty)=each(%pets)) { while(my($cmp_pet. end of hash pet='cats'. pet='dogs'. pet='cats'. dogs=>1. and the process repeats itself indefinitely. and gets "fish". } } } > > > > > > > > > there there there there there there there there . which means calling each() on a hash in a loop that then calls each() on the same hash another loop will cause problems. The inside loop calls each() and gets "dogs". pet='dogs'. The inside loop calls each() one more time and gets an empty list."than $cmp_pet\n". ).> > > > > > > > pet='cats'. pet='dogs'. The inside loop exits.

The inner loop continues to call each() until it gets the key that matches the outer loop key.One solution for this each() limitation is shown below. dogs=>1. or some similar problem. my %pets = ( fish=>3. and loop through the array of keys using foreach. } else { print "there are less $orig_pet " ."than $cmp_pet\n". 46 . either because its in someone else's code and they do not pass it to you. last if($cmp_pet eq $orig_pet).$orig_qty)=each(%pets)) { while(1) { my($cmp_pet. store the keys in an array. cats=>2. next unless(defined($cmp_pet)). while(my($orig_pet. The inner loop must skip the end of the hash (an undefined key) and continue the inner loop."than $cmp_pet\n". The inner loop will then not rely on the internal hash iterator value.$cmp_qty)=each(%pets). This also fixes a problem in the above example in that we probably do not want to compare a key to itself. } } } > > > > > > there there there there there there are are are are are are more less less less more more cats cats dogs dogs fish fish than than than than than than dogs fish fish cats cats dogs If you do not know the outer loop key. ). then the only other solution is to call keys on the hash for all inner loops. if($orig_qty>$cmp_qty) { print "there are more $orig_pet " .

butter is the order of scalars in @cart1 and the order of the scalars at the beginning of @checkout_counter. 'dogs'.2. but there is no way to know. using the first scalar as a key and the following scalar as its value. Basically. and so on throughout the list. However. list context can be extremely handy. The initial values for the hash get converted into an ordered list of scalars ( 'fish'. 2. The original container that held the scalars is forgotten. cats=>2. > 'juice' > ]. and all the contents of @checkout_counter could belong to @cart2. my @cart1 = qw( milk bread eggs). 'cats'. print Dumper \@checkout_counter. Sometimes. Everything in list context gets reduced to an ordered series of scalars. In fact. dogs=>1 ).4 List Context List context is a concept built into the grammar of perl. there is no way to know where the contents of @cart1 end and the contents of @cart2 begin. two people with grocery carts. In the above example the order of scalars is retained: milk. pulled up to the @checkout_counter and unloaded their carts without putting one of those separator bars in between them. looking at just @checkout_counter. bread. > 'bacon'. @cart2 ). 47 . Here is an example. List context affects how perl executes your source code. You cannot declare a "list context" in perl the way you might declare an @array or %hash. my @cart2=qw( eggs bacon juice ). > 'butter'. > 'eggs'. We have used list context repeatedly to initialize arrays and hashes and it worked as we would intuitively expect: my %pets = ( fish=>3. 1 ) These scalars are then used in list context to initialize the hash. The person behind the @checkout_counter has no idea whose groceries are whose. 3. > 'bread'. @cart1 and @cart2. my @checkout_counter = ( @cart1. my @cart1=qw( milk bread butter). > $VAR1 = [ > 'milk'. @cart1 might have been empty.

List context applies anytime data is passed around in perl. Scalars, arrays, and hashes are all affected by
list context. In the example below, @house is intended to contain a list of all the items in the house.
However, because the %pets hash was reduced to scalars in list context, the values 3,2,1 are
disassociated from their keys. The @house variable is not very useful.
my %pets = ( fish=>3, cats=>2, dogs=>1 );
my @refrigerator=qw(milk bread eggs);
my @house=('couch',%pets,@refrigerator,'chair');
print Dumper \@house;
>$VAR1 = [
>
'couch',
>
'cats',
>
2,
>
'dogs',
>
1,
>
'fish',
>
3,
>
'milk',
>
'bread',
>
'eggs',
>
'chair'
> ];
There are times when list context on a hash does make sense.
my %encrypt=(tank=>'turtle',bomber=>'eagle');
my %decrypt=reverse(%encrypt) ;
print Dumper \%decrypt;
> $VAR1 = {
>
'eagle' => 'bomber',
>
'turtle' => 'tank'
> };
The %encrypt hash contains a hash look up to encrypt plaintext into cyphertext. Anytime you want to
use the word "bomber", you actually send the word "eagle". The decryption is the opposite. Anytime
you receive the word "eagle" you need to translate that to the word "bomber".
Using the %encrypt hash to perform decryption would require a loop that called each() on the %encrypt
hash, looping until it found the value that matched the word received over the radio. This could take too
long.
Instead, because there is no overlap between keys and values, (two different words don't encrypt to the
same word), we can simply treat the %encrypt hash as a list, call the array reverse() function on it,
which flips the list around from end to end, and then store that reversed list into a %decrypt hash.

48

2.5 References
References are a thing that refer (point) to something else.
The "something else" is called the "referent", the thing being pointed to.
Taking a reference and using it to access the referent is called "dereferencing".
A good real-world example is a driver's license. Your license "points" to where you live because it lists
your home address. Your license is a "reference". The "referent" is your home. And if you have
forgotten where you live, you can take your license and "dereferencing" it to get yourself home.
It is possible that you have roommates, which would mean multiple references exist to point to the
same home. But there can only be one home per address.
In perl, references are stored in scalars. You can create a reference by creating some data (scalar, array,
hash) and putting a "\" in front of it.
my %home= (
fish=>3,cats=>2,dogs=>1,
milk=>1,bread=>2,eggs=>12,
);
my $license_for_alice = \%home;
my $license_for_bob = \%home;
Alice and Bob are roommates and their licenses are references to the same %home. This means that
Alice could bring in a bunch of new pets and Bob could eat the bread out of the refrigerator even
though Alice might have been the one to put it there. To do this, Alice and Bob need to dereference
their licenses and get into the original %home hash.
$ {$license_for_alice} {dogs} += 5;
delete($ {$license_for_bob} {milk});
print Dumper \%home;
> $VAR1 = {
>
'eggs' => 12,
>
'cats' => 2,
>
'bread' => 2,
>
'dogs' => 6,
>
'fish' => 3
> };

49

2.5.1 Named Referents
A referent is any original data structure: a scalar, array, or hash. Below, we declare some named
referents: age, colors, and pets.
my $age = 42;
my @colors = qw( red green blue );
my %pets=(fish=>3,cats=>2,dogs=>1);

2.5.2 References to Named Referents
A reference points to the referent. To take a reference to a named referent, put a "\" in front of the
named referent.
my $ref_to_age = \$age;
my $r_2_colors = \@colors;
my $r_pets = \%pets;

2.5.3 Dereferencing
To dereference, place the reference in curly braces and prefix it with the sigil of the appropriate type.
This will give access to the entire original referent.
${$ref_to_age}++; # happy birthday
pop(@{$r_2_colors});
my %copy_of_pets = %{$r_pets};
print "age is '$age'\n";
> age is '43'
If there is no ambiguity in dereferencing, the curly braces are not needed.
$$ref_to_age ++; # another birthday
print "age is '$age'\n";
> age is '44'

50

2. %pets=(fish=>3. This: ${$r_pets} {dogs} += 5. To create an anonymous array referent.dogs=>1). ${$r_pets} {dogs} += 5. Take the reference. Because array and hash referents are so common.cats=>2. my %pets=(fish=>3. 'dogs' => 6. Each named referent has a reference to it as well.4 Anonymous Referents Here are some referents named age. $r_pets = \%pets. colors. # green turned to yellow 'blue' ]. @colors = qw( red green blue ). is exactly the same as this: $r_pets->{dogs} += 5. my $r_colors = \@colors. 'yellow'.dogs=>1). It is also possible in perl to create an ANONYMOUS REFERENT. and then follow that by either "[index]" or "{key}". follow it by "->". $r_age = \$age.cats=>2. print Dumper \%pets. my $r_pets = \%pets. ${$r_colors}[1] = 'yellow'. my my my my my my $age = 42. 51 . > $VAR1 = [ 'red'.It is also possible to dereference into an array or hash with a specific index or key. and pets. An anonymous referent has no name for the underlying data structure and can only be accessed through the reference. ${$r_colors}[1] = 'yellow'. $r_colors = \@colors. $VAR1 = { 'cats' => 2. my @colors = qw( red green blue ). put the contents of the array in square brackets. # 5 new dogs 'fish' => 3 }. perl has a shorthand notation for indexing into an array or looking up a key in a hash using a reference. $r_colors->[1] = 'yellow'.5. print Dumper \@colors.

my $pets_ref = { fish=>3. 52 . put the contents of the hash in curly braces. but that array has no name to directly access its data. 'green'. my $colors_ref = [ 'red'. > 'fish' => 3 > }. You must use $pets_ref to access the data in the hash.dogs=>1 }. > 'dogs' => 1. print Dumper $colors_ref. > 'blue' > ]. Likewise. Note that $colors_ref is a reference to an array. You must use $colors_ref to access the data in the array. but that hash has no name to directly access its data. $pets_ref is a reference to a hash. print Dumper $pets_ref. > 'green'. The curly braces will create the underlying hash with no name. and return a reference to that unnamed hash.The square brackets will create the underlying array with no name.cats=>2. To create an anonymous hash referent. > $VAR1 = { > 'cats' => 2. 'blue' ]. > $VAR1 = [ > 'red'. and return a reference to that unnamed array.

Using references is one way to avoid the problems associated with list context. but now using references. > 'fish' => 3 > }. The $house variable is a reference to an anonymous hash. Dereferencing a complex data structure can be done with the arrow notation or by enclosing the reference in curly braces and prefixing it with the appropriate sigil. These keys are associated with values that are references as well. > 'refrigerator' => [ > 'milk'. 53 . But because scalars can hold references. which contains two keys. print Dumper $house. dogs=>1 ). my %pets = ( fish=>3. > $VAR1 = { > 'pets' => { > 'cats' => 2.2.5. > 'eggs' > ] > }. Here is another look at the house example. > 'dogs' => 1. one a hash reference and the other an array reference. refrigerator=>\@refrigerator }. "pets" and "refrigerator".5 Complex Data Structures Arrays and hashes can only store scalar values. my @refrigerator=qw(milk bread eggs). # Alice added more canines $house->{pets}->{dogs}+=5. cats=>2. # Bob drank all the milk shift(@{$house->{refrigerator}}). my $house={ pets=>\%pets. > 'bread'. complex data structures are now possible.

as if it were a reference to an array of a hash of an array of a hash of an array. Perl will assume you know what you are doing with your structures. we start out with an undefined scalar called $scal. If this is NOT what you want to do. my $val = $scal->[2]->{somekey}->[1]->{otherkey}->[1]. > { > 'otherkey' => [] > } > ] > } > ]. > { > 'somekey' => [ > ${\$VAR1->[0]}. > ${\$VAR1->[0]}. > $VAR1 = [ > undef.5. print Dumper $scal. We then fetch from this undefined scalar. 54 . my $scal. Perl autovivifies everything under the assumption that that is what you wanted to do.2.5. check for the existence of each hash key and check that the array contains at least enough array entries to handle the given index.1 Autovivification Perl autovivifies any structure needed when assigning or fetching from a reference. In the example below. The autovivified referents are anonymous.

$j++) { for(my $k=0. col=1. > $VAR1 = [ > [ > [ > 'row=0.5. depth=1' > ].$i<2. my $mda.$k++){ $mda->[$i]->[$j]->[$k] = "row=$i. col=1. depth=0'. col=1. > [ > [ > 'row=1. depth=0'. 55 . col=0.5. > [ > 'row=0. > 'row=0. col=0. col=0. > 'row=1. > [ > 'row=1. depth=1' > ] > ].$i++){ for(my $j=0.$j<2. col=$j. depth=1' > ]. col=1. depth=1' > ] > ] > ]. > 'row=0. } } } print Dumper $mda. col=0. > 'row=1. depth=$k".2 Multidimensional Arrays Perl implements multidimensional arrays using one-dimensional arrays and references. depth=0'. depth=0'.$k<2. for(my $i=0.2.

my $reference = \$referent. my $scal. indicating you want to import the 'nstore'. nstore ($scal. $scal->[2]->{somekey}->[1]->{otherkey}->[1].5. reboot computer. my $value = $$reference. use Storable qw(nstore dclone retrieve).pm module also contains two subroutines for storing the contents of any perl data structure to a file and retrieving it later. warn "reference is '$reference'". read the section about CPAN later in this document. 2.5.4 Data Persistence The Storable.6 Stringification of References Perl will stringify a reference if you try to do anything string-like with it. and install. 'filename'). use the Storable. 2. for now. my $reference = 'SCALAR(0x812e6ec)'. Deep Copy If you need to create an entirely separate but identical clone of a complex data structure. use Storable qw(nstore dclone retrieve). # exit. such as print it. The 'use' statement is explained later in this document as well.8 installed. Storable comes standard with perl 5. But perl will not allow you to create a string and attempt to turn it into a reference. my $referent = 42. download Storable from CPAN. and 'retrieve' subroutines. consider an upgrade. The 'dclone' subroutine takes a reference to any kind of data structure and returns a reference to a deep cloned version of that data structure. If you don't have 5.8. Otherwise.5.5. and restart script my $revived = retrieve('filename').pm perl module. my $scal. Then use Storable in your perl code... # $twin is an identical clone of $scal my $twin = dclone $scal.3 Deep Cloning. 'dclone'. > Can't use string ("SCALAR(0x812e6ec)") as > a SCALAR ref while "strict refs" in use 56 . $scal->[2]->{somekey}->[1]->{otherkey}->[1].5.2. > reference is 'SCALAR(0x812e6ec)' . it isn't that important.

no strict. warn "string is '$string'". print "string is '$string'\n". my $string = ref($temp). 57 . which is always false. what_is_it( [1. But if you call ref() on a nonreference. my $temp = \42. If the scalar is not a reference.2.5. Instead of SCALAR(0x812e6ec). even if the value to which it points is false. } what_is_it( \'hello' ). what_is_it( {cats=>2} ).7 The ref() function The ref() function takes a scalar and returns a string indicating what kind of referent the scalar is referencing. its just SCALAR.3] ). ref() returns false (an empty string). warn "value is '$value'\n". 2.Turning strict off only gives you undef. my $value = $$reference. > value not defined > Use of uninitialized value in concatenation Because a reference is always a string that looks something like "SCALAR(0x812e6ec)". > string is 'SCALAR' > string is 'ARRAY' > string is 'HASH' > string is '' Note that this is like stringification of a reference except without the address being part of the string. warn "value not defined" unless(defined($value)). you get an empty string. > string is 'SCALAR' Here we call ref() on several types of variable: sub what_is_it { my ($scalar)=@_. you get the scalar value. it will evaluate true when treated as a boolean. what_is_it( 42 ). Also note that if you stringify a non-reference. my $reference = 'SCALAR(0x812e6ec)'. my $string = ref($scalar).

if( $price == 0 ) { print "Free Beer!\n". my $greeting = "Hello. my $name = 'John Smith'. print $greeting. $name\n".3 Control Flow Standard statements get executed in sequential order in perl. } 58 . Control flow statements allow you to alter the order of execution while the program is running.

Perl supports the following control flow structures: ## LABEL is an optional name that identifies the # control flow structure. see arrays and # list context sections later in text LABEL foreach (LIST) BLOCK LABEL foreach VAR (LIST) BLOCK LABEL foreach VAR (LIST) BLOCK continue BLOCK 59 .. TEST... # It is a bareword identifier followed by a colon... } LABEL BLOCK LABEL BLOCK continue BLOCK # BOOL ==> boolean (see boolean section above) SINGLE_STATEMENT if (BOOL). # example==> MY_NAME: ## SINGLE_STATEMENT ==> a single perl statement # NOT including the semicolon. TEST.... # print "hello\n" ## BLOCK ==> zero or more statements contained # in curly braces { print "hi". CONT ) BLOCK # LIST is a list of scalars. if (BOOL) BLOCK if (BOOL) BLOCK else BLOCK if (BOOL) BLOCK elsif (BOOL) BLOCK elsif (). if (BOOL) BLOCK elsif (BOOL) BLOCK . unless (BOOL) BLOCK elsif (BOOL) BLOCK . CONT are all expressions # INIT is an initialization expression # INIT is evaluated once prior to loop entry # TEST is BOOLEAN expression that controls loop exit # TEST is evaluated each time after # BLOCK is executed # CONT is a continuation expression # CONT is evaluated each time TEST is evaluated TRUE LABEL for ( INIT. else BLOCK LABEL while (BOOL) BLOCK LABEL while (BOOL) BLOCK continue BLOCK LABEL until (BOOL) BLOCK LABEL until (BOOL) BLOCK continue BLOCK # INIT. else BLOCK unless (BOOL) BLOCK unless (BOOL) BLOCK else BLOCK unless (BOOL) BLOCK elsif (BOOL) BLOCK elsif ().

3 next LABEL. If the structure has a LABEL. A label is an identifier followed by a colon.2 last LABEL. you can call next. redo LABEL.4 redo LABEL. execution starts the next iteration of the control construct if it is a loop construct. redo. Inside a BLOCK of a control flow structure. then the command will operate on the control structure given.3. last. last LABEL.1 Labels Labels are always optional. 3. If no label is given to next. A label is used to give its associated control flow structure a name. 3. execution resumes there. if there is a continue block. It does not execute any continue block (even if it exists). Execution then resumes at the start of the control structure without evaluating the conditional again. then the command will operate on the inner-most control structure. last. The next command skips the remaining BLOCK. It does not execute any continue block if one exists. you can call next LABEL. 3. or if no continue block exists. or redo. The redo command skips the remaining BLOCK. 60 . After the continue block finishes. The last command goes to the end of the entire control structure. If a label is given.

@other_package::refrigerator.1 Package Declaration Perl has a package declaration statement that looks like this: package NAMESPACE. perl assumes it is in the the most recently declared package namespace that was declared. followed by the variable name. and Data::Dumper are attached to the namespace in which they were turned on with "use warnings. The standard warnings. strictness. All perl scripts start with an implied declaration of: package main. you will want to "use" these again. use warnings. $package_this::age. %package_that::pets. followed by a double colon. This package declaration indicates that the rest of the enclosing block. warn "The value is '$some_package::answer'\n". 61 . or file belongs to the namespace given by NAMESPACE. followed by the package name. there are two ways to create and use package variables: 1) Use the fully package qualified name everywhere in your code: # can use variable without declaring it with 'my' $some_package::answer=42. package SomeOtherPackage. This is called a package QUALIFIED variable meaning the package name is explicitly stated." etc. subroutine.4 Packages and Namespaces and Lexical Scoping 4. If you use an UNQUALIFIED variable in your code. use strict. When you have strict-ness turned on. You can access package variables with the appropriate sigil. eval. use Data::Dumper. Anytime you declare a new package namespace.

. { # START OF CODE BLOCK package Heifers. package this_package. To encourage programmers to play nice with each other's namespaces.. then you will need to declare the package namespace explicitly. as example (2) above refers to the $name package variable. once a package variable is declared with "our". Using "our" is the preferred method. that package namespace declaration remains in effect until the end of the block. our $speak = 'moo'. You can even declare variables in someone else's package namespace. If the namespace is other than "main". 62 . the package namespace reverts to the previous namespace. the fully package qualified name is NOT required. our $name='John'. The difference between the two methods is that always using package qualified variable names means you do NOT have to declare the package you are in. at which time. the "our" function was created. warn "name is '$name'".2 Declaring Package Variables With our 2) Use "our" to declare the variable. } # END OF CODE BLOCK warn "speak is '$speak'". package Hogs. without ever having to declare the namespace explicitly.0 or later for "our" declarations. we can access it any way we wish. and you can refer to the variable just on its variable name. Declaring a variable with "our" will create the variable in the current namespace. > Hogs::speak is 'oink' . However. The "our" declaration is a shorthand for declaring a package variable. You must have perl 5. our $speak = 'oink'. There is no restrictions in perl that prevent you from doing this. You can create variables in ANY namespace you want. We do not HAVE to use the "our" shortcut even if we used it to declare it. 4.6. > speak is 'oink' . our $speak = 'oink'.4.3 Package Variables inside a Lexical Scope When you declare a package inside a code block. warn "Hogs::speak is '$Hogs::speak'". package Hogs.. Once the package variable exists..

Outside those curly braces. In the above examples. So "lexical scope" refers to anything that is visible or has an effect only withing a certain boundary of the source text or source code. things that have lexical limitations (such as a package declaration) are only "visible" inside that lexical space. and we now have to use a fully package qualified name to get to the variables in Heifers package.5 Lexical Variables Lexical variables are declared with the “my” keyword. A lexical scope exists while execution takes place inside of a particular chunk of source code. no warnings. and to show how lexical variables differ from "our" variables. { my $speak = 'moo'. Its just that outside the code block.The Heifers namespace still exists. We had to turn warnings and strict off just to get it to compile because with warnings and strict on. as in telescope. The package variables declared inside the code block "survive" after the code block ends. no strict. Within a lexical scope. 4. the "package Heifers. The easiest way to demonstrate lexical scoping is lexical variables." declaration has worn off. the "our Heifers. > Heifers::speak is 'moo' 4. as does all the variables that were declared in that namespace. Lexical variables declared inside a lexical scope do not survive outside the lexical scope. our $speak = 'moo'. Scope refers to vision. perl will know $speak does not exist when you attempt to print it. 63 ." only exists inside the curly braces of the source code. so it does not exist when we try to print it out after the block. } warn "speak is '$speak'\n". } print "Heifers::speak is '$Heifers::speak'\n". so it will throw an exception and quit. { package Heifers. This "wearing off" is a function of the code block being a "lexical scope" and a package declaration only lasts to the end of the current lexical scope. the package declaration has gone out of scope. > speak is '' The lexical variable "$speak" goes out of scope at the end of the code block (at the "}" character). which is a technical way of saying its "worn off".4 Lexical Scope Lexical refers to words or text.

for (1 . Package variables are permanent. or file. it is created dynamically. package main. warn "main::cnt is '$main::cnt'". Note in the example below. They generally keep you from stepping on someone else's toes. { my $some_lex = 'I am lex'. eval. and $lex_var is at a different address each time. we create a new $lex_var each time through the loop. > some_lex is '' 3) Lexical variables are subject to "garbage collection" at the end of scope. no strict. 64 . > main::cnt is '' 2) Lexical variables are only directly accessible from the point where they are declared to the end of the nearest enclosing block. push(@cupboard. subroutine. The example below shows that “my $cnt” is not the same as the “main::cnt”: no warnings.Lexically scoped variables have three main features: 1) Lexical variables do not belong to any package namespace. my @cupboard. so you cannot prefix them with a package name. my $cnt='I am just a lexical'. during execution. print "$lex_ref\n". They also keep your data more private than a package variable. never go out of scope. my $lex_ref = \$lex_var. and are accessible from anyone's script. $lex_ref).. perl will remove it from its memory. } warn "some_lex is '$some_lex'". } > SCALAR(0x812e770) > SCALAR(0x812e6c8) > SCALAR(0x812e6e0) > SCALAR(0x81624c8) > SCALAR(0x814cf64) Lexical variables are just plain good. If nothing is using a lexical variable at the end of scope. Every time a variable is declared with "my". The location of the variable will change each time. never get garbage collected. 5) { my $lex_var ='canned goods'.

If a lexical variable is a referent of another variable. it remains under perl's jurisdiction. 4.6 Garbage Collection When a lexical variable goes out of scope. ($first. The example below shows two variables that refer to each other but nothing refers to the two variables. But since $referring_var is a reference to $some_lex. This means that your program will never get smaller because of lexical variables going of of scope. Once the memory is allocated for perl. { my $some_lex = 'I am lex'. rather the freed up memory is used for possible declarations of new lexically scoped variables that could be declared later in the program. > some_lex is '' > referring var refers to 'I am lex' When the lexical $some_lex went out of scope. Perl will not garbage collect these variables even though they are completely inaccessible by the end of the code block. warn "referring var refers to '$$referring_var'". } warn "some_lex is '$some_lex'". The freed up memory is not returned to the system.$last).$last)=(\$last. perl will delete that variable and free up memory. no strict.6. } 65 . my $referring_var. Note that the named variable $some_lex went out of scope at the end of the code block and could not be accessed by name.\$first). then $some_lex was never garbage collected. $referring_var=\$some_lex. we could no longer access it directly. and if no one is using it. perl will check to see if anyone is using that variable. The data in $some_lex was still accessible through referring_var.1 Reference Count Garbage Collection Perl uses reference count based garbage collection. { my ($first. But perl can use garbage collected space for other lexical variables. so circular references will not get collected even if nothing points to the circle. then the lexical will not be garbage collected when it goes out of scope. It is rudimentary reference counting.4. and it retained its value of "I am lex".

{ my $cnt=0. print "cnt is '$cnt'\n". The inc and dec subroutines are subroutine closures.} sub dec{$cnt--.2 Garbage Collection and Subroutines Garbage collection does not rely strictly on references to a variable to determine if it should be garbage collected. Subroutines that use a lexical variable declared outside of the subroutine declaration are called "CLOSURES". the only things that can access it after the code block are the subroutines. however perl knows that $cnt is needed by the subroutines and therefore keeps it around. dec. inc. once declared. Therefore.6. sub inc{$cnt++. > cnt > cnt > cnt > cnt > cnt > cnt is is is is is is '1' '2' '3' '2' '1' '2' Subroutine names are like names of package variables. print "cnt is '$cnt'\n". Since $cnt goes out of scope. is declared inside a code block and would normally get garbage collected at the end of the block. inc. inc. the lexical variable. 66 . dec.} } inc. Note that a reference to $cnt is never taken.4. named subroutines are like package variables in that. The subroutine gets placed in the current declared package namespace. they never go out of scope or get garbage collected. In the example below. $cnt. then that variable will not be garbage collected as long as the subroutine exists. If a subroutine uses a lexical variable. two subroutines are declared in that same code block that use $cnt. so $cnt is not garbage collected. However.

these subroutines print little or no information.7 Package Variables Revisited Package variables are not evil. } } sub Link { if ($Development::Verbose){ print "linking\n". They are global. and they inherit all the possible problems associated with using global variables in your code. If this variable is true. 67 . these subroutines print detailed information. If it is false.4. Imagine several subroutines across several files that all want to check a global variable: $Development::Verbose. our $Verbose=1. they do have some advantages. Link. } } sub Run { if ($Development::Verbose){ print "running\n". which means they can be a convenient way for several different blocks of perl code to talk amongst themselves using an agreed upon global variable as their channel. they are just global variables. Run. > compiling > linking > running The three subroutines could be in different files. In the event you DO end up using a package variable in your code. and they could all access the $Development::Verbose variable and act accordingly. in different package namespaces. sub Compile { if ($Development::Verbose) { print "compiling\n". package Development. } } Compile.

Link. saves off the original value. and then sets $Development::Verbose back to its original value. set it to a new and temporary value. and then set the global back to what it was. our $Verbose=1. sub Compile { if ($Development::Verbose) { print "compiling\n". } Compile. Run. } } sub Link { if ($Development::Verbose){ print "linking\n". RunSilent. } } sub Run { if ($Development::Verbose){ print "running\n". calls the original Run routine. there are times when you want to save the current value of the global variable. The RunSilent subroutine could be written like this: sub RunSilent { local($Development::Verbose)=0. Run. the original value for the variable is returned. $Development::Verbose=$temp. allows you to assign a temp value to it. } } sub RunSilent { my $temp = $Development::Verbose. That new value is seen by anyone accessing the variable. $Development::Verbose=0. Continuing the previous example.4. The local function takes a package variable. say we wish to create a RunSilent subroutine that stores $Development::Verbose in a temp variable. And at the end of the lexical scope in which local() was called. 68 . > compiling > linking This can also be accomplished with the "local()" function. execute some foreign code that will access this global.8 Calling local() on Package Variables When working with global variables. package Development.

5. 5 Subroutines Perl allows you to declare named subroutines and anonymous subroutines. Local is also a good way to create a temporary variable and make sure you don't step on someone else's variable of the same name. 5. and hashes are mandatory. or with a fully package qualified name if you are outside the package. you may access it with just NAME if you are in the correct package. arrays. package MyArea. > ping > ping > ping > ping 69 . perl was given the local() function. similar to the way you can declare named variables and anonymous variables. So once a named subroutine is declared. sub Ping {print "ping\n".1 Subroutine Sigil Subroutines use the ampersand ( & ) as their sigil.} Ping. But while the sigils for scalars. &Ping. in the same way "our" variables go into the current package namespace. So to deal with all the package variables.} Perl originally started with nothing but package variables. The NAME of the subroutine is placed in the current package namespace. the sigil for subroutines is optional.2 Named Subroutines Below is the named subroutine declaration syntax: sub NAME BLOCK NAME can be any valid perl identifier. &MyArea::Ping. MyArea::Ping. And you can use the optional ampersand sigil in either case. BLOCK is a code block enclosed in parenthesis. The "my" lexical variables were not introduced until perl version 4.

} my $temp = sub {print "Hello\n". > $VAR1 = sub { "DUMMY" }.3 Anonymous Subroutines Below is the anonymous subroutine declaration syntax: sub BLOCK This will return a code reference. sub Ping {print "ping\n". For this reason.Once the current package declaration changes. what_is_it($temp). arrays. a subroutine can be declared with a prototype. Instead Data::Dumper does not even try and just gives you a place holder that returns a dummy string. > ref returned 'CODE' 5. similar to how [] returns an array reference. 5. my $temp = sub {print "Hello\n". all arguments go through the list context crushing machine and get reduced to a list of scalars. &MyArea::Ping.}. The subroutine will not know if the list of scalars it receives came from scalars.} package YourArea. things like Data::Dumper cannot look inside the code block and show you the actual code. or hashes. 70 . # error. print "ref returned '$string'\n". and similar to how {} returns a hash reference.}.4 Data::Dumper and subroutines The contents of the code block are invisible to anything outside the code block. package MyArea.5 Passing Arguments to/from a Subroutine Any values you want to pass to a subroutine get put in the parenthesis at the subroutine call. The original containers are not known inside the subroutine. which are discussed later. print Dumper $temp. For normal subroutines. you MUST use a fully package qualified subroutine name to call the subroutine. my $string = ref($scalar). &Ping. MyArea::Ping. To avoid some of the list context crushing. sub what_is_it { my ($scalar)=@_. looking in current package YourArea > ping > ping > Undefined subroutine &YourArea::Ping 5.

6 Accessing Arguments inside Subroutines via @_ Inside the subroutine.$left). my $two = "I am two". the preferred way to extract them is to assign @_ to a list of scalars with meaningful names. assigning a value to an element in @_ will change the value in the original variable that was passed into the subroutine call. } The @_ array is "magical" in that it is really a list of aliases for the original arguments passed in. sub swap { my ($left. &{$temp}. my $temp = sub {print "Hello\n".7 Dereferencing Code References Dereferencing a code reference causes the subroutine to be called. > one is 'I am two' > two is 'I am one' Assigning to the entire @_ array does not work.}.$two). } my $one = "I am one". Subroutine parameters are effectively IN/OUT.5. warn "two is '$two'". $temp->(). sub compare { my ($left. you have to assign to the individual elements. these arguments fit nicely into an array. If swap were defined like this. the arguments are accessed via a special array called @_.$right)=@_. the variables $one and $two would remain unchanged. @_ = ($right. warn "one is '$one'". return $left<=>$right. swap($one. The @_ array can be processed just like any other regular array. since all the arguments passed in were reduced to list context. A code reference can be dereferenced by preceding it with an ampersand sigil or by using the arrow operator and parenthesis ">()". If the arguments are fixed and known. #WRONG } 5.$right)=@_. Therefore. The preferred way is to use the arrow operator with parens. # preferred > Hello > Hello > Hello 71 . sub swap { (@_) = reverse(@_). &$temp.

'two' ). # doesn't look like I'm passing any params # but perl will pass @_ implicitly.2. &second_level. # pass nothing.5. This generally is not a problem with named subroutines because you probably will not use the "&" sigil. sub second_level { print Dumper \@_. the arrow operator is the preferred way to dereference a code reference. > $VAR1 = [ > 1. However. } sub first_level { # using '&' sigil and no parens. This can cause subtly odd behavior if you are not expecting it. dereferencing using the "&" may cause implied arguments to be passed to the new subroutine. > 3 > ]. For this reason.3). no implicit @_ $code_ref->(@_).8 Implied Arguments When calling a subroutine with the "&" sigil prefix and no parenthesis. } first_level(1. $code_ref->(). # explicitly pass @_ $code_ref->( 'one'. when using code references. the current @_ array gets implicitly passed to the subroutine being called. > 2. # pass new parameters 72 .

# undef or empty list } my $scal_var = this_is_false.0 or "") will work in scalar context. it will create an array with the first element set to undef. An explicit return statement is the preferred approach if any return value is desired. The return value can be explicit. 73 . print Dumper \$scal_var. or it can be implied to be the last statement of the subroutine. In boolean context. The problem is that the subroutine needs to know if it is called in scalar context or array context. > 3 > ]. } my @arr_var =ret_arr.10 Returning False The return value of a subroutine is often used within a boolean test.2. print Dumper \@arr_var. but in array context. > $VAR1 = \'boo'.3). # return a single scalar sub ret_scal { return "boo". This is the preferred way to return false in a subroutine. > $VAR1 = [ > 1. an array with one or more elements is considered true. # return a list of values sub ret_arr { return (1.9 Subroutine Return Value Subroutines can return a single value or a list of values. A return statement by itself will return undef in scalar context and an empty list in list context. my @arr_var = this_is_false.5. 5. Returning a simple "undef" value (or 0 or 0. } my $scal_var = ret_scal. sub this_is_false { return. > 2.

disregard $bitmask internal use only. The caller() function returns a list of information in the following order 0 1 2 3 4 5 6 7 8 9 $package package namespace at time of call $filename filename where called occurred $line line number in file where call occurred $subroutine name of subroutine called $hasargs true if explicit arguments passed in $wantarray list=1. >$VAR1 = [ > 'main'. and it occurred at line 13 of the file.11 Using the caller() Function in Subroutines The caller() function can be used in a subroutine to find out information about where the subroutine was called from and how it was called.pl.pl'. The package qualified name of the subroutine that was called was main::HowWasICalled. the default package namespace. sub HowWasICalled { my @info = caller(0). > 'main::HowWasICalled'. > 2. that information is hidden in lexical scope. Caller takes one argument that indicates how far back in the call stack to get its information from. use caller(0). void=undef $evaltext evaluated text if an eval block $is_require true if created by "require" or "use" $hints internal use only. For information about the current subroutine. 74 .5. The package qualified name must be given since you don't know what package is current where the subroutine was called from. > undef. > undef. disregard Note in the example above. The call occurred in package main. print Dumper \@info. the code is in a file called test. > 'UUUUUUUUUUUU' > ]. > 1. } HowWasICalled. > '. scalar=0. > 13. > undef./test.

5.12 The caller() function and $wantarray
The argument of interest is the $wantarray argument. This indicates what return value is expected of
the subroutine from where it was called. The subroutine could have been called in void context
meaning the return value is thrown away. Or it could have been called and the return value assigned to
a scalar. Or it could have been called and the return value assigned to a list of scalars.
sub CheckMyWantArray {
my @info = caller(0);
my $wantarray = $info[5];
$wantarray='undef' unless(defined($wantarray));
print "wantarray is '$wantarray'\n";
}
CheckMyWantArray; #undef
my $scal = CheckMyWantArray; # 0
my @arr = CheckMyWantArray; # 1
> wantarray is 'undef'
> wantarray is '0'
> wantarray is '1'

5.13 Context Sensitive Subroutines with wantarray()
You can use the wantarray variable from caller() to create a subroutine that is sensitive to the context in
which it was called.
sub ArrayProcessor {
my @info = caller(0);
my $wantarray = $info[5];
return unless(defined($wantarray));
if($wantarray) {
return @_;
} else {
return scalar(@_);
}
}
my @arr=qw(alpha bravo charlie);
ArrayProcessor(@arr);
my $scal = ArrayProcessor(@arr); # 3
my @ret_arr = ArrayProcessor(@arr); # alpha ...
print "scal is '$scal'\n";
print Dumper \@ret_arr;
> scal is '3'
>$VAR1 = [
> 'alpha',
> 'bravo',
> 'charlie'
> ];
75

6 Compiling and Interpreting
When perl works on your source code, it will always be in one of two modes: compiling or interpreting.
Perl has some hooks to allow access into these different cycles. They are code blocks that are prefixed
with BEGIN, CHECK, INIT, and END.
Compiling: translating the source text into machine usable internal format.
Interpreting: executing the machine usable, internal format.
The BEGIN block is immediate.
BEGIN -> execute block as soon as it is compiled, even before compiling anything else.
The other blocks, including normal code, do not execute until after the entire program has been
compiled. When anything other than a BEGIN block is encountered, they are compiled and scheduled
for execution, but perl continues compiling the rest of the program. The execution order is CHECK,
INIT, normal code, and END blocks.
CHECK -> Schedule these blocks for execution after all source code has been compiled.
INIT-> Schedule these blocks for execution after the CHECK blocks have executed.
normal code -> Schedule normal code to execute after all INIT blocks.
END -> Schedule for execution after normal code has completed.
Multiple BEGIN blocks are executed immediately in NORMAL declaration order.
Multiple CHECK blocks are scheduled to execute in REVERSE declaration order.
Multiple INIT blocks are scheduled to execute in NORMAL declaration order.
Multiple END blocks are scheduled to execute in REVERSE declaration order.

76

An example containing several CHECK, INIT, normal code, and END blocks. The output shows the
execution order:
END { print "END 1\n" }
CHECK { print "CHECK 1\n"
BEGIN { print "BEGIN 1\n"
INIT { print "INIT 1\n" }
print "normal\n";
INIT { print "INIT 2\n" }
BEGIN { print "BEGIN 2\n"
CHECK { print "CHECK 2\n"
END { print "END 2\n" }
> BEGIN 1
> BEGIN 2
> CHECK 2
> CHECK 1
> INIT 1
> INIT 2
> normal
> END 2
> END 1

}
}

}
}

77

Generally. These declared subroutines can be called and public variables can be accessed by any perl script that uses the module. Perl Modules Lets say you come up with some really great chunks of perl code that you want to use in several different programs." otherwise you will get a compile error: Dog. The module then declares a subroutine called "Speak". A perl module is really just a file with an invented name and a ". 78 .pm" extension. # MUST BE LAST STATEMENT IN FILE All perl modules must end with "1. use warnings. 8 The use Statement The "use" statement allows a perl script to bring in a perl module and use whatever declarations have been made available by the module. The best place to put code to be used in many different programs is in a "Perl Module". use Data::Dumper. Perhaps you have some subroutines that are especially handy.pm and script.pl could bring in the Dog module like this: use Dog. Continuing our example.. etc. The "pm" is short for "perl module".7 Code Reuse. If you had some handy code for modeling a dog. would have to be in the same directory. The content of a perl module is any valid perl code. After any new package declaration you will need to turn on warnings.pm did not return a true value . ###filename: Dog. Dog::Speak. you might put it in a module called Dog.pm package Dog. use strict. and then you would use the "use" statement to read in the module. a file called script. such as subroutine declarations and possibly declarations of private or public variables.pl. like any normal subroutine.pm. which. Once the Dog module has been used. perl modules contain declarations.. } 1. Dog. Dog. It is standard convention that all perl modules start out with a "package" declaration that declares the package namespace to be the same as the module name. The Dog module declares its package namespace to be Dog. Here is an example of our Dog module. and perhaps they have some private data associated with them. > Woof! Both files. anyone can call the subroutine by calling Dog::Speak. and then "use" that module. sub Speak { print "Woof!\n". ends up in the current package namespace.

So perl would look for Pets::Dog::GermanShepard in Pets/Dog/ for a file called GermanShepard. Because the "require" statement is in a BEGIN block. User created module names should be mixed case. So this will not work: push(@INC. Pets::Dog. The "require" statement is what actually reads in the module file. 79 . Module names with all lower case are reserved for built in pragmas. "require" will translate the double colons into whatever directory separator is used on your system.'/home/username/perlmodules')." Module names with all upper case letters are just ugly and could get confused with built in words. meaning it would be either a single identifier or multiple identifiers separated by double-colons. it will execute immediately after being compiled.9 The use Statement. MODULENAME->import( LISTOFARGS ).pm 9. use Dogs. you can add this subdirectory to @INC and perl will find any modules located there. it would be a "/". Perl will initialize this array to some default directories to look for any modules. Pets::Cat::Persian. such as "use warnings. } The MODULENAME follows the package namespace convention. When performing the search for the module file. If you want to create a subdirectory just for your modules. though. Formally The "use" statement can be formally defined as this: use MODULENAME ( LISTOFARGS ). For Linux style systems.1 The @INC Array The "require" statement will look for the module path/file in all the directories listed in a global array called @INC. The "use" statement is exactly equivalent to this: BEGIN { require MODULENAME. These are all valid MODULENAMES: use use use use Dog. Pets::Dog::GermanShepard.

Because the require statement is in a BEGIN block. The MODULENAME->import statement is then executed. Perl does not understand it.'/home/username/perlmodules'). } use Dogs.3 The PERL5LIB and PERLLIB Environment Variables The "require" statement also searches for MODULENAME in any directories listed in the environment variable called PERL5LIB. because it does not need a BEGIN block. If you don't have PERL5LIB set. You could say something like this: BEGIN { push(@INC. 80 . use Dogs. Also. Any code that is not a declaration will execute at this point. so @INC will not be changed when "use" is called. 9. perl compiles it.This is because the "push" statement will get compiled and then be scheduled for execution after the entire program has been compiled. note that the home directory symbol "~" is only meaningful in a linux shell. before the "push" is executed. The "use" statement will get compiled and executed immediately. you will need to call "glob" to translate "~" to something perl will understand. 9. for you Linux heads. perl will search for MODULENAME in any directory listed in the PERLLIB environment variable. Just say something like this: use lib '/home/username/perlmodules'. So if you want to include a directory under your home directory. The PERL5LIB variable is a colon separated list of directory paths. The "glob" function uses the shell translations on a path. This means any executable code gets executed.4 The require Statement Once the require statement has found the module. Consult your shell documentation to determine how to set this environment variable.2 The use lib Statement The "use lib" statement is my preferred way of adding directory paths to the @INC array. use lib glob('~/perlmodules'). 9. the module gets executed immediately as well.

This happens when you use Data::Dumper in your script. which has not been introduced yet. Which is why you can say use Data::Dumper. one of the bells and whistles of a method call is a thing called "inheritance". print Dumper \@var. if your perl module declares a subroutine called "import" then it will get executed at this time.9. if your perl module OR ITS BASE CLASS(ES) declares a subroutine called "import" then it will get executed at this time. More advancedly. which has not been introduced yet. instead of having to say: use Data::Dumper. Basically. print Data::Dumper::Dumper \@var. 81 . A subroutine called "Dumper" from the package Data::Dumper gets imported into your package namespace.5 MODULENAME -> import (LISTOFARGS) The MODULENAME->import(LISTOFARGS) statement is a "method call". So. The import method is a way for a module to import subroutines or variables to the caller's package. to be more accurate. A method call is a fancy way of doing a subroutine call with a couple of extra bells and whistles bolted on.

print Dumper \@_. print "with the following args\n". warn "executing normal code". #!/usr/local/env perl ###filename:script. use Data::Dumper. > with the following args > $VAR1 = [ > 'Dog'. > calling import at Dog. ###filename:Dog.pm line 7.pl line 6.pm package Dog. > Woof! 82 . sub Speak { print "Woof!\n". use warnings.pl use warnings. Dog::Speak. > 'GermanShepard' > ]. use strict. use strict. warn "just before use Dog".9. > just after use Dog at .6 The use Execution Timeline The following example shows the complete execution timeline during a use statement.pl line 4. use Dog ('GermanShepard'). } sub import { warn "calling import". use Data::Dumper. > just before use Dog at . } 1.pm line 4./script. #MUST BE LAST STATEMENT IN FILE > executing normal code at Dog. warn "just after use Dog"./script.

HASH.10 bless() The bless() function is so simple that people usually have a hard time understanding it because they make it far more complicated than it really is. warn ref(sub{}). STRING. ref() will return SCALAR. > ARRAY at . > str is 'ARRAY' Normally. The bless() function is the basis for Object Oriented Perl./script. $rarr=\@arr.2. > SCALAR at . but bless() by itself is overwhelmingly simple. The bless function takes a reference and a string as input. ARRAY.3). warn ref({}). warn ref(\4). > HASH at ./script.pl line 5. All bless does is change the string that would be returned when ref() is called. > '' at ./script. or empty-string depending on what type of referent it is referred to.pl line 4.ref(4). my @arr=(1. bless REFERENCE./script.pl line 7. # reference to referent my $str = ref($rarr). # referent my $rarr = \@arr. warn ref([]). 83 . Quick reference refresher: Given an array referent. @arr.pl line 6. # call ref() warn "str is '$str'". warn "'"./script. The bless function will then return the original reference. then calling ref($rarr) will return the string "ARRAY". CODE. > CODE at ."'". The bless function modifies the referent pointed to by the reference and attaches the given string such that ref() will return that string. and a reference.pl line 8.

warn ref(bless([].3). warn ref(bless(\$sca./script. Note this is exactly the same as the code in the first example.2.pl line 8. and because of that name it might be used differently. we can call ref() on the return value and accomplish it in one line: my $sca=4./script. # reference to referent bless($rarr. > Box at . the referent might be used differently or behave differently. In perl.pl line 7. but with one line added to do the bless: my @arr=(1. my $str = ref($rarr). warn ref(bless({}. The constitution and makeup of the water did not change."Curlies"))./script. bless() changes the name of a referent. We will see this difference with method calls./script. It does not affect the contents of the referent. 84 . That is it. You might be wondering why the word "bless" was chosen. # referent my $rarr = \@arr. > str is 'Counter' Since bless() returns the reference. then people would refer to it as "holy water"."Box")). All bless() does is affect the value returned by ref(). > Action at .pl line 5. # call ref() warn "str is '$str'". only the name returned by ref(). > Four at .Here is an example of bless() in action. But because of this new name. warn ref(bless(sub{}."Action")). > Curlies at . however it was given a new name.pl line 6. "Counter")."Four")). If a religious figure took water and blessed it.

sub Speak { print Dumper \@_. the INVOCANT always gets unshifted into the @_ array in the subroutine call. > Woof So it is almost the same as using a package qualified subroutine name Dog::Speak. Quick review of package qualified subroutine names: When you declare a subroutine. use warnings. use strict. } Dog -> Speak (3). Or you can use the fully qualified package name. it goes into the current package namespace. Dog -> Speak. and be guaranteed it will work every time. but an INVOCANT can be many different things. The MODULENAME->import(LISTOFARGS) was a method call.11 Method Calls We have seen method calls before. So what is different? First. sub Speak { print "Woof\n". 85 . package Dog. but the simplest thing it can be is just a bareword package name to go look for the subroutine called METHOD. # INVOCANT > 3 # first user argument > ]. some more useful than others. This may not seem very useful. } Speak. Here is the generic definition: INVOCANT -> METHOD ( LISTOFARGS ). You can call the subroutine using its short name if you are still in the package. An invocant can be several different things. > $VAR1 = [ > 'Dog'. Dog::Speak. but we had to do some handwaving to get beyond it. > Woof > Woof A method call is similar. calling it a fancy subroutine call. The INVOCANT is the thing that "invoked" the METHOD. The second difference between a subroutine call and a method call is inheritance. use Data::Dumper. package Dog.

pl use Shepard. sub Speak { my ($invocant. Notice that script.pl called Shepard->Speak. Shepard->Track. 86 . Say we model a German Shepard that has the ability to track a scent better than other breeds. warn "invocant is '$invocant'".pm line 8. When script.11. sub Track { warn "sniff. not Dog.pl used Shepard.pm line 6. } 1. use warnings. But German Shepards still bark like all dogs.pm package Dog. sniff at Shepard. use base Dog. Also notice that the subroutine Dog::Speak received an invocant of "Shepard". It did not find one.pm package Shepard. use Data::Dumper. > Woof at Dog. Even though perl ended up calling Dog::Speak. The specific breeds of dogs will likely be able to inherit some behaviors (subroutine/methods) from a base class that describes all dogs. The unexplained bit of magic is that inheritance uses the "use base" statement to determine what packages to inherit from. Shepard INHERITED the Speak subroutine from the Dog package. > Woof at Dog. So then it looked and found a BASE of Shepard called Dog. It then looked for a subroutine called Dog::Speak. ###filename:Shepard. and called that subroutine. found one. for(1 . $count) { warn "Woof".1 Inheritance Say you want to model several specific breeds of dogs.pm line 4. } } 1. $count) = @_. > invocant is 'Shepard' at Dog.pl always used Shepard as the invocant for its method calls. sniff". Shepard->Speak(2). use strict. #!/usr/local/env perl ###filename:script. perl first looked in the Shepard namespace for a subroutine called Shepard::Speak.. which was "Shepard" in this case. > sniff. And script. perl still passes Dog::Speak the original invocant. ###filename:Dog.pm line 8.

MODULENAME). The @ISA array is named that way because "Shepard" IS A "Dog".MODULENAME) is new. left-to-right. push(@ISA. is functionally identical to this: BEGIN { require MODULENAME. so you will want to learn it.11. The @ISA array contains any packages that are BASE packages of the current package.2 use base This statement: use base MODULENAME. This is not necessarily the "best" way to search. therefore ISA. When a method call looks in a package namespace for a subroutine and does not find one. you can change it with a module from CPAN. it will then go through the contents of the @ISA array. If this approach does not work for your application. 87 . but it is how perl searches. The search order is depth-first. } The require statement goes and looks for MODULENAME.pm using the search pattern that we described in the "use" section earlier. The push(@ISA.

# FALSE (can't track a scent) 11.pm => MothersFather. Child->isa("MothersMother").pm => @ISA = Father.pm => @ISA = FathersFather.Imagine a Child module has the following family inheritance tree: Child.5 Interesting Invocants So far we have only used bareword invocants that correspond to package names. # TRUE (Woof) Child->can("Track"). MothersFather MothersMother ). # FALSE 11. perl will call ref() on the reference and use the string returned as starting package namespace to begin searching for the method/subroutine.pm => qw ( qw ( qw ( @ISA @ISA @ISA @ISA Father Mother ). Shepard->can("Speak").pm => FathersMother.pm => @ISA = Mother. Well. Perl will search for Child->Method through the inheritance tree in the following order: Child Father FathersFather FathersMother Mother MothersFather MothersMother 11. 88 .4 INVOCANT->can(METHODNAME) The "can" method will tell you if the INVOCANT can call METHODNAME successfully.3 INVOCANT->isa(BASEPACKAGE) The "isa" method will tell you if BASEPACKAGE exists anywhere in the @ISA inheritance tree. FathersFather FathersMother ). = (). = (). # TRUE Child->isa("Shepard"). Remember bless() changes the string returned by ref(). when using a reference as an invocant. Perl allows a more interesting invocant to be used with method calls: a blessed referent. = ().pm => MothersMother. Shepard->Track. = ().

Here is our simple Dog example but with a blessed invocant.
###filename:Dog.pm
package Dog;
use warnings; use strict; use Data::Dumper;
sub Speak {
my ($invocant, $count) = @_;
warn "invocant is '$invocant'";
for(1 .. $count) { warn "Woof"; }
} 1;
#!/usr/local/env perl
###filename:script.pl
use Dog;
my $invocant=bless {},'Dog'; ### BLESSED INVOCANT
$invocant->Speak(2);
> invocant is 'Dog=HASH(0x8124394)' at Dog.pm line 6
> Woof at Dog.pm line 8.
> Woof at Dog.pm line 8.
The my $invocant=bless {},"Dog"; is the new line. The bless part creates an anonymous
hash, {}, and blesses it with the name "Dog". If you called ref($invocant), it would return the string
"Dog".
So perl uses "Dog" as its "child" class to begin its method search through the hierarchy tree. When it
finds the method, it passes the original invocant, the anonmous hash, to the method as the first
argument.
Well, since we have an anonymous hash passed around anyway, maybe we could use it to store some
information about the different dogs that we are dealing with. In fact, we already know all the grammar
we need to know about Object Oriented Perl Programming, we just need to speak different sentences
now.

89

12 Procedural Perl
So far, all the perl coding we have done has been "procedural" perl. When you hear "procedural" think
of "Picard", as in Captain Picard of the starship Enterprise. Picard always gave the ship's computer
commands in the form of procedural statements.
Computer, set warp drive to 5.
Computer, set shields to "off".
Computer, fire weapons: phasers and photon
torpedoes.
The subject of the sentences was always "Computer". In procedural programming, the subject
"computer" is implied, the way the subject "you" is implied in the sentence: "Stop!"
The verb and direct object of Picard's sentences become the subroutine name in proceedural
programming. Whatever is left become arguments passed in to the subroutine call.
set_warp(5);
set_shield(0);
fire_weapons qw(phasers photon_torpedoes);

13 Object Oriented Perl
Object oriented perl does not use an implied "Computer" as the subject for its sentences. Instead, it uses
what was the direct object in the procedural sentences and makes it the subject in object oriented
programming.
Warp Drive, set yourself to 5.
Shields, set yourself to "off".
Phasors, fire yourself.
Torpedoes, fire yourself.
But how would we code these sentences?

90

Here is a minimal example of object oriented perl. There is a class called “Animal”. It has a constructor
called MakeNew and a method called Speak. The script uses the Animal module, creates instances of
Animal objects, and calls the Speak method on each one.
###filename:Animal.pm
package Animal;
sub MakeNew {
my ($invocant,$name)=@_;
my $object = {};
$object->{Name}=$name;
bless($object, $invocant);
return $object;
}
sub Speak {
my ($obj)=@_;
my $name = $obj->{Name};
print "$name growls\n";
}
1;

#
#
#
#
#
#

our constructor
class and name are passed in
hash to store data
put name into hash
bless hash into class
return hash/instance/object

#
#
#
#

some method
hash/instance/object passed in
get name of this instance
say who is speaking

#!/usr/local/env perl
###filename:script.pl
use Animal;
# note that 'Animal' is passed in to MakeNew
# as first parameter. 'Samson' is second parameter.
# 'Animal' becomes $invocant. 'Samson' becomes $name.
my $lion = Animal->MakeNew('Samson'); # create an instance
# note that the blessed hash reference, $lion, is passed
# into Speak method as first parameter. It becomes $obj.
$lion->Speak(); # call method on this instance
my $tiger = Animal->MakeNew('Fuzzball');
$tiger->Speak();
my $bear = Animal->MakeNew('Smokey');
$tiger->Speak();
> Samson growls
> Fuzzball growls
> Smokey growls

91

We then add a method to let dogs bark. and returns a reference to the hash. This subroutine is an object contructor. Then we create a Dog module that uses Animal as its base to get the contructor. The method prints the name of the dog when they bark so we know who said what. But once you start adding things like inheritance and polymorphism. Lets return to a familiar example. rather than as individually named variables. puts the Name into a hash. so we create an Animal. This return value becomes a "Animal" object. we want a common way to handle all pets. This module contains one subroutine that takes the invocant and a Name. the advantages of object oriented become more obvious. The first thing we want to do is process objects as an array. our Dog module. Assume we want to keep track of several dogs at once.So what? Basic Object Oriented does nothing that cannot be just as easily done in procedural perl.pm perl module. blesses the hash. 92 . Perhaps we are coding up an inventory system for a pet store. First.

pm package Animal. > Fluffy says Woof at Dog.pm line 7.$invocant).$name)=@_. } 1. sub Speak { my ($obj)=@_. Dog->New($name)). because if you translated that statement to English. sub New { my ($invocant. warn "$name says Woof". #!/usr/local/env perl ###filename:script. } # have every pet speak for themselves. The script then goes through the array and calls the Speak method on each object.The script. } > Butch says Woof at Dog.pm line 7.pm package Dog. ###filename:Dog. 93 . } 1. use base Animal. Object Oriented Programming statements are of the form: $subject -> verb ( adjectives. # create 3 Dog objects and put them in @pets array foreach my $name qw(Butch Spike Fluffy) { push(@pets.pm line 7. my $name=$obj->{Name}. This is object oriented programming. etc ). it would be "Pet. adverbs. return bless({Name=>$name}. Notice the last foreach loop in script. foreach my $pet (@pets) { $pet->Speak. my @pets. > Spike says Woof at Dog. The subject of the sentence is "Pet". rather than the implied "Computer" of procedural programming. speak for yourself". ###filename:Animal.pl creates three dogs and stores them in an array.pl says $pet->Speak.pl use Dog.

Fluffy says Meow at Cat.pm package Cat.pm line 7. If it's an OO package. Then we modify script. Fang says Meow at Cat. # polymorphism at work } > > > > > > Butch says Woof at Dog. } # have all the pets say something. 13. } # create some cat objects foreach my $name qw(Fang Furball Fluffy) { push(@pets. #!/usr/local/env perl ###filename:script. Expanding our previous example. you can call it a “class”.pm line 7. we might want to add a Cat class to handle cats at the pet store. } 1. use base Animal. my @pets. Fluffy says Woof at Dog.pm line 7. Furball says Meow at Cat. foreach my $pet (@pets) { $pet->Speak.2 Polymorphism Polymorphism is a real fancy way of saying having different types of objects that have the same methods. #create some dog objects foreach my $name qw(Butch Spike Fluffy) { push(@pets. A perl package that is designed for procedural use is simply called a package.13. sub Speak { my $obj=shift.pm line 7. warn "$name says Meow".pl use Dog. 94 . use Cat.pl to put some cats in the @pets array. my $name=$obj->{Name}. Spike says Woof at Dog. ###filename:Cat. Cat->New($name)). Dog->New($name)).1 Class The term "class" refers to a perl package/module that is used in an object oriented way.pm line 7.pm line 7.

use Shepard. my $dog=Shepard->New("Spike"). #!/usr/local/env perl ###filename:script. The Shepard module uses Dog as its base. To shorten the example. and then calls its ancestor's Dog version of speak. But this scatters hardcoded names of the base class throughout Shepard. 95 .pm line 6.$_[0]). ###filename:Shepard. This is polymorphism. And each object just knows how to do what it should do. } sub Speak { my $name=$_[0]->{Name}. the animal will say whatever is appropriate for its type. the only way that Shepard can call Dog's version of speak is to use a fully package qualified name Dog::Speak().pm package Dog. the constructor New was moved to Dog.pm package Shepard. use strict. ###filename:Dog. > Spike says Woof at Dog. use base Dog. } 1. The code processes a bunch of objects and calls the same method on each object. which would make changing the base class a lot of work. sub Speak { my $name=$_[0]->{Name}. ### SUPER } 1.pm line 8.pl use warnings. Without the magic of SUPER. sub New { return bless({Name=>$_[1]}. and has a Speak method that growls. $_[0]->SUPER::Speak. warn "$name says Woof". $dog->Speak.3 SUPER SUPER:: is an interesting bit of magic that allows a child object with a method call that same method name in its parent's class. > Spike says Grrr at Shepard. 13.Notice how the last loop goes through all the pets and has each one speak for themselves.pm. warn "$name says Grrr". Whether its a dog or cat. use Data::Dumper. Back to the dogs.

Many times a class might exist that does ALMOST what you want it to do. So designing Father to rely on his future. it is legitimate to have what you might consider to be "universal" methods that exist for every class. "look at my ancestors and call their version of this method. built-in way to do this in perl.pm" module available on CPAN. and FathersFather. could be considered a bad thing. the only modules that will get looked at is "FathersFather" and "FathersMother". In that case. you might want a method that calls its parent method but then multiplies the result by minus one or something. Rather than modify the original code to do what you want it to. SUPER will do the trick. I will refer you to the "NEXT. This could be considered a good thing. Imagine an object of type "Child". When Father was coded. SUPER is a way of saying. then SUPER will not work. you could instead create a derived class that inherits the base class and rewrite the method to do what you want it to do. and so on and so forth. If "Father" has a method called Speak and that method calls SUPER::Speak. have-not-evenmet-her-yet mother-in-law." There are some limitations with SUPER. In cases like this. Instead of a class called "Child" imagine a class called "CoupleAboutToGetMarried". However. every class could do its part. FathersMother.If Shepard's version of Speak simply said $_[0]->Speak. The FatherOfTheBride would pay for the wedding. Father and Mother as parents. MothersMother was a complete stranger he would not meet for years to come. Unfortunately. and then call SUPER::ContributeToWedding. Consider the big family tree inheritance diagram in the "use base" section of this document (the one with Child as the root. and every base class has a method called "ContributeToWedding". etc as grandparents). it would get into an infinite loop calling itself recursively. since you would assume that Father was designed only knowing about FathersFather and FathersMother. SUPER looks up the hierarchy starting at the class from where it was called. This means if the method FathersFather needed to call was in MothersMother. 96 . the FatherOfTheGroom would pay for the rehersal dinner. there is no easy. For example. SUPER does have its uses. though.

perl silently moves on and cleans up the object data. and the object is scheduled for garbage collection. If Mother and Father both have a DESTROY method.$_[0]). Just prior to deleting the object and any of its internal data." has been sold"). ###filename:Dog. With an object that has a complex hierarchical family tree. perl will only call the FIRST method of DESTROY that it finds in the ancestry. The DESTROY method has similar limitations as SUPER.13. } sub DESTROY { warn (($_[0]->{Name}). use Dog. 97 . use strict. use Data::Dumper. The NEXT. } 1. my $dog=Dog->New("Spike").4 Object Destruction Object destruction occurs when all the references to a specific object have gone out of lexical scope. perl will call the DESTROY method on the object.pm package Dog.pm line 7.pm module on CPAN also solves this limitation. $dog=undef. sub New { return bless({Name=>$_[1]}. If no such method exists. > Spike has been sold at Dog.pl use warnings. #!/usr/local/env perl ###filename:script. then Mother's not going to handle her demise properly and you will likely have ghosts when you run your program.

1 Modules The basis for code reuse in perl is a module. "Spike". The object is usually a hash.pm class. The best way of calling a constructor is to use the arrow operator: my $object = Classname->Constructor(arguments). one key was "Name". this would look like: my $pet = Animal->New('Spike') The name of the constructor can be any valid subroutine name. If the module is designed for object oriented use." The "use" statement will look for the module in the directories listed in the PERL5LIB environment variable and then the directories listed in the @INC variable. 98 . Keys to the hash correspond to object attribute names.3 bless / constructors If the module is designed for procedural programming. and so on.14 Object Oriented Review 14. and different instances had Name values of "Fluffy". The best way to add directories to the @INC variable is to say use lib "/path/to/dir".pm module example. Constructors are subroutines that create a reference to some variable. and then return the reference. it will provide subroutine declarations that can be called like normal subroutines. and the Values correspond to the attribute values specific to that particular instance. Once its referent is blessed. In the Animal.2 use Module The code in a perl module can be made available to your script by saying "use MODULE. Any double-colons (::) in the module name being used get converted to a directory separator symbol of the operating system. 14. and the reference is a handy way of passing the object around. then the module is sometimes referred to as a "class". 14. The module can be designed for procedural programming or object oriented programming (OO). If the module is OO. it can be used as an object. but is usually "new" or "New". In the Animal. A perl module is a file that ends in ". it will declare subroutines that will be used as constructors or methods. use the reference to bless the variable into the class.pm" and declares a package namespace that (hopefully) matches the name of the file.

A method is simply a subroutine that receives a reference to the instance variable as its first argument. The preferred way of calling a method is using the arrow method. change values. etc. methods can be called on the instance to get information. The classes Cat and Dog inherit from the base class Animal. 99 . 14. then a derived class can override the base class method by declaring its own subroutine called MethodName.14. If a base class contains a method called "MethodName".6 Overriding Methods and SUPER Classes can override the methods of their base classes. In the Animal.4 Methods Once an instance of an object has been constructed. Cat and Dog are "derived" from Animal. 14. In the above examples. If a derived class overrides a method of its base class. it may want to call its base class method. "Speak" was a method that used the Name of the instance to print out "$name says woof". This allows many similar classes to put all their common methods in a single base class. the Cat and Dog classes both inherit from a common Animal class. perform operations. Methods should be thought of as "actions" to be performed on the instance. Both Dog and Cat classes inherit the constructor "New" method from the Animal base class. the GermanShepard derived class overrode the Dog base class Speak method with its own method. To have a class inherit from a base class. The GermanShepard method named Speak called the Dog version of Speak by calling: $obj->SUPER::Speak.5 Inheritance Classes can inherit methods from base classes. In one example above. The only way to accomplish this is with the SUPER:: pseudopackage name. use base BaseClassName. this would look like: $pet->Speak. In the examples above. use the "use base" statement. or "verbs" in a sentences with instances being the "subject". $ObjectInstance -> Method ( list of arguments ).pm example.

60 From here. if available. and then set your PERL5LIB environment variable to point to that directory. most modules install with the exact same commands: > > > > > > perl Makefile. source code to install perl. FAQs. there is a "h2xs" utility. Once you find a module that might do what you need.1 CPAN.gz (you should use the latest version. then you can copy the .org CPAN contains a number of search engines. which will be a file with a tar. Here is the standard installation steps for a module.) > gunzip NEXT-0.cpan. and most importantly. The "exit" step is shown just so you remember to log out from root. which is "Plain Old Documentation" embedded within the perl modules downloaded from CPAN.pm module is a module that automates the installation process. you can view the README file that is usually available online before actually downloading the module. and it downloads it from the web.60. untars it. and installs it for you. If you install a module that requires a separate module. which contains a plethora of perl module for anyone to download. 100 .15 CPAN CPAN is an acronym for "Comprehensive Perl Archive Network". it installs both modules for you with one command. More interestingly.pm module. then download the tarball.tar.gz > tar -xf NEXT-0.60. There is a CPAN website. 15.tar.gz extension. The Web Site CPAN is a website that contains all things perl: help.60. a plethora of perl module so that you can re-use someone else's code. And finally. There is also a CPAN perl module. it will install any dependencies for you as well. This example is for the NEXT. A "perldoc" utility comes with perl that allows viewing of POD.2 CPAN.pm file). which provides a shell interface for automating the downloading of perl modules from the CPAN website. http://www. which automates the creation of a module to be uploaded to CPAN. If you do not have root privileges and the module is pure perl (just a .pm file to your home directory (or anywhere you have read/write privileges). If the README looks promising. which is contained in NEXT-0.tar > cd NEXT-0.PL make make test su root make install exit The "make install" step requires root privileges. The Perl Module The CPAN. 15. you give it the name of a module.

CPAN. it will ask you a bunch of configuration questions. which is an Internet file transfer program for scripts.CPAN.pm module shell. The CPAN. > su root > perl -MCPAN -e shell The first time it is run. Most can be answered with the default value (press <return>). Change to root.pm module is run from a shell mode as root (you need root privileges to do the install). and then run the CPAN.pm will also want ncftpget. Install these on your system before running the CPAN module. Lynx is a text-based webbrowser.pm will want you to have lynx installed on your machine. 101 .

102 .PL? [0] Your ftp_proxy? Your http_proxy? Your no_proxy? Select your continent (or several nearby continents) [] > 5 Select your country (or several nearby countries) [] > 3 Select as many URLs as you like.PL' command? Your choice: [] Parameters for the 'make' command? Your choice: [] Parameters for the 'make install' command? Your choice: [] Timeout for inactivity during Makefile.cpan] Cache size for build directory (in MB)? [10] Perform cache scanning (atstart or never)? [atstart] Cache metadata (yes/no)? [yes] Your terminal expects ISO-8859-1 (yes/no)? [yes] Policy on building prerequisites (follow. put them on one line.informatik. ask or ignore)? [ask] Where is your gzip program? [/usr/bin/gzip] Where is your tar program? [/bin/tar] Where is your unzip program? [/usr/bin/unzip] Where is your make program? [/usr/bin/make] Where is your lynx program? [] > /usr/bin/lynx Where is your wget program? [/usr/bin/wget] Where is your ncftpget program? [] > /usr/bin/ncftpget Where is your ftp program? [/usr/bin/ftp] What is your favorite pager program? [/usr/bin/less] What is your favorite shell? [/bin/bash] Parameters for the 'perl Makefile.uni-dortmund. it will go directly to the cpan shell prompt.de:1404] cpan> That last line is actually the cpan shell prompt. separated by blanks [] > 3 5 7 11 13 Enter another URL or RETURN to quit: [] Your favorite WAIT server? [wait://ls6-www. The next time you run cpan.Here is a log from the CPAN being run for the first time on my machine: Are you ready for manual configuration? [yes] CPAN build and cache directory? [/home/greg/.

# go to make directory perl Makefile.pm # edit module cd . At the cpan shell prompt. You do not need to know POD to write perl code. > perldoc perldoc > perldoc NEXT > perldoc Data::Dumper 15... If you wish to force the install.tar. perl comes with a utility "h2xs" which. If cpan encounters any problems.cpan. Perl comes with a builtin utility called "perldoc" which allows you to look up perl documentation in POD format. The remainder of the commands show you what steps you need to take to create a .4 Creating Modules for CPAN with h2xs If you wish to create a module that you intend to upload to CPAN. But you will want to know how to read POD from all the modules you download from CPAN. 15.gz tarball that can be uploaded to CPAN and downloaded by others using the cpan. then use the "force" command.3 Plain Old Documentation (POD) and perldoc Modules on CPAN are generally documented with POD. will create a minimal set of all the files needed. This first command will create a directory called "Animal" and populate it with all the files you need. POD embeds documentation directly into the perl code. > > > > > > > > > > h2xs -X -n Animal # create the structure cd Animal/lib # go into module dir edit Animal.pm module. it will not install the module.PL # create make file make # run make make test # run the test in t/ make dist # create a .gz file 103 . among other things.tar. cpan> force install Tk Or you can get the tarball from www.org and install it manually. type the following command: cpan> install Bundle::CPAN cpan> reload cpan You should then be able to install any perl module with a single command./t # go into test dir edit Animal.t # edit test cd .pm module with all the trimmings.The first thing you will probably want to do is make sure you have the latest and greatest cpan.

> anotherscript. > mytest.pl -f optionfile.txt -. Options can be stored in a separate file. A "-in" switch might be followed by a filename to be used as input.txt -v Options can have full and abbreviated versions to activate the same option. The option "-verbose" can also work as "-v".+define+FAST More advanced arguments: Single character switches can be lumped together. > thisscript. This would allow a user to use the option file and then add other options on the command line.txt -f = options. A file might contain a number of options always needed to do a standard function. any new topics may include a discussion of a perl builtin feature or something available from CPAN. > myscript. -f=options.pl -v Switches might by followed by an argument associated with the switch. The "--" argument could be used to indicate that arguments before it are to be used as perl arguments and that arguments after it are to be passed directly to a compiler program that the script will call.txt An argument could indicate to stop processing the remaining arguments and to process them at a later point in the script. 17 Command Line Arguments Scripts are often controlled by the arguments passed into it via the command line when the script is executed. Some of perl's builtin features are somewhat limited and a CPAN module greatly enhances and/or simplifies its usage. you could say "-xyz".pl -in test42. > thatscript. Instead of "-x -y -z".txt 104 . and using "-f optionfile.16 The Next Level You now know the fundamentals of procedural perl and object oriented perl.pl -h A "-v" switch might turn verboseness on. Options operate independent of spacing. From this point forward.txt" would be easier than putting those options on the command line each and every time that function is needed. such as "-h" to get help. Arguments might be a switch.pl -in data.

txt then you will need to put it in quotes or your operating system will replace it with a list of files that match the wildcard pattern. If you need to pass in a wild-card such as *. use Data::Dumper. The text on the command line is broken up anywhere whitespace occurs. 'test.pl use warnings. .pl -v -f options.pl "*. > script.pl'. > 'hello world' > ].txt'. #!/usr/bin/env perl ###filename:script. > '-f'./test. use strict.txt "hello world" > $VAR1 = [ > '-v'. print Dumper \@ARGV.pl *.pl' ]. use Data::Dumper.17.pl' ].pl $VAR1 = [ 'script. > 'options. use strict. 105 . #!/usr/bin/env perl ###filename:script.1 @ARGV Perl provides access to all the command line arguments via a global array @ARGV. except for quoted strings. > > > > > > > > > . print Dumper \@ARGV.pl" $VAR1 = [ '*.pl use warnings./test.

If you need to support more advanced command line arguments. } # get the first/next argument and process it.} elsif($arg eq '-d') {$debug=1. # create a package variable for each option our $fn. our $debug=0. The following example will handle simple command line arguments described above. or a lot of simple ones. you would want this to turn on debugging in any separate modules that you write. Outside of package main.Simple processing of @ARGV would shift off the bottom argument.} else { die "unknown argument '$arg'". process it. you should look at Getopt::Declare. Package "main" is the default package and a good place to put command line argument related variables. 106 . If you wrote a script that used "-d" to turn on debug information. then the above example of processing @ARGV one at a time is probably sufficient.pl script. and move on to the next argument. if($arg eq '-h') {print_help. } } Package (our) variables are used instead of lexical (my) variables because command line arguments should be considered global and package variables are accessible everywhere.} elsif($arg eq '-f') {$fn = shift(@ARGV). If you need to handle a few simple command line arguments in your script. # create subroutines for options that do things sub print_help { print "-d for debug\n-f for filename\n". not just your script. while(scalar(@ARGV)) { my $arg=shift(@ARGV). code would check for $main::debug being true or false.

our $debug=0. the global variables $fn and $debug are used with their full package name. This is because Getopt::Declare recognizes -h to print out help based on the declaration. not that the starting curly brace must begin on its own line separate from the argument declaration and description. This string defines the arguments that are acceptable. print "Debug is '$debug'\n". but will still be recognized if placed on the command line 107 . my $args = Getopt::Declare->new( q ( -in <filename> Define input file {$main::fn=$filename.} <unknown> { die "unknown arg '$unknown'\n". The text within the curly braces {$main::fn=$filename. Also. } )). If [undocumented] is contained anywhere in the command line argument description. Notice that -h is not defined in the string.2 Getopt::Declare The Getopt::Declare module allows for an easy way to define more complicated command line arguments. The above example with -h. and -d options could be written using Getopt::Declare like this: use Getopt::Declare. our $fn=''. > script. The text passed into Getopt::Declare is a multi-line quoted q() string.pl -h >Options: > -in <filename> Define input file > -d Turn debugging On The argument declaration and the argument description is separated by one or more tabs in the string passed into Getopt::Declare. arguments that are not defined in the declaration. Getopt::Declare recognizes -v as a version command line argument.} is treated as executable code and evaled if the declared argument is encountered on the command line.} -d Turn debugging On {$main::debug=1.-f.17. then that argument will not be listed in the help text. Note that within the curly braces. it will print out the version of the file based on $main::VERSION (if it exists) and the date the file was saved. The <unknown> marker is used to define what action to take with unknown arguments. print "fn is '$fn'\n". If -v is on the command line.

4. 5.(secret arguments) A [ditto] flag in the description will use the same text description as the argument just before it. Filenames to be handled by the script can be listed on the command line without any argument prefix 2. 108 . A short and long version of the same argument can be listed by placing the optional second half in square brackets: -verb[ose] This will recognize -verb and -verbose as the same argument. Normally. calling finish() with a true value will cause the command line arguments to stop being processed at that point. It can be turned off with -quiet. The Error() subroutine will report the name of the file containing any error while processing the arguments. Additional arguments can be placed in an external file and loaded with -args filename. 3. Any options after a double dash (--) are left in @ARGV for later processing. An undocumented -Dump option turns on dumping. Verbosity can be turned on with -verbose. and any action associated with it. 1. allowing nested argument files. 6. a declared argument will only be allowed to occur on the command line once. Argument files can refer to other argument files. If the argument can occur more than once. 17. place [repeatable] in the description.1 Getopt::Declare Sophisticated Example The example on the next page shows Getopt::Declare being used more to its potential. Any arguments that are not defined will generate an error.2. Inside the curly braces.

main::Verbose ("returning to '$main::arg_file'\n").} -quiet Turn verbose Off {$main::verbose=0. sub Verbose {if($verbose){print $_[0].01.['-BUILD']).} } ). our $dump=0." from '$arg_file'\n". our $VERSION=1. } -d Turn debugging On {$main::debug=1.} -h Print Help {$main::myparser->usage. 109 .$unknown).} -.} main::Verbose("Parsing '$input'\n").} <unknown> Filename [repeatable] { if($unknown!~m{^[-+]}) {push(@main::files.Argument separator {finish(1). { local($main::arg_file). our $verbose=0. our $debug=0.} -verb[ose] Turn verbose On {$main::verbose=1. $main::arg_file = $input.} my $grammar = q( -args <input> Arg file [repeatable] { unless(-e $input) {main::Error("no file '$input'"). our $myparser = new Getopt::Declare ($grammar.} --Dump [undocumented] Dump on {$main::dump=1.}} sub Error {die"Error: ".($_[0]). $main::myparser->parse([$input]). our $arg_file='Command Line'. $myparser->parse(). } main::Verbose ("finished parsing '$input'\n").} else {main::Error("unknown arg '$unknown'").# advanced command line argument processing use Getopt::Declare. # -v will use this our @files.

18 File Input and Output Perl has a number of functions used for reading from and writing to files. you can read from a filehandle a number of ways. is the first character of the string. The filename is a simple string. or append. The valid flags are defined as follows: '<' Read.2 close Once open. <$filehandle> When used as the boolean conditional controlling a while() loop. If no flag is specified. The second argument to open() is the name of the file and an optional flag that indicates to open the file as read. 18. and the scalar goes out of scope or is assigned undef. 'filename.1 open To generate a filehandle and attach it to a specific file. The most common is to read the filehandle a line at a time using the "angle" operator. Create if non-existing. i. DEFAULT. if present.txt') or die "Could not open file". the loop reads the filehandle a line at a time until the end of file is reached. If the filehandle is stored in a scalar. use the open() function. 18. then perl will automatically close the filehandle for you. Do not clobber existing file. you can close a filehandle by calling the close function and passing it the filehandle.6 and later and is the preferred method for dealing with filehandles. and the flag. Create if non-existing. close($filehandle) or die "Could not close". '>>' Append. 18. the file defaults to being opened for read. Do not create. 110 . Do not clobber existing file. write. The angle operator is the filehandle surrounded by angle brackets. Clobber if already exists. Each pass through the conditional test reads the next line from the file and places it in the $_ variable. '>' Write.3 read Once open. All file IO revolves around file handles. This is available in perl version 5.e. perl will create a filehandle and assign it to that scalar. If the first argument to open() is an undefined scalar. open(my $filehandle.

chomp($line). return $line. age: $age\n". and you are just going through each line and parsing it. you can write to the filehandle using the print function. You can then call the subroutine each time you want a line. while(<$fh>) { $num++. defined(my $line = <$fh>) or die "premature eof". 'input. This will read the next line from the filehandle. print $fh "upon\n". print "$num: $line\n". and you need to read it in a certain order. address: $addr. otherwise you hit the end of file. open (my $fh. sub nlin { defined(my $line =<$fh>) or croak "premature eof". } The above example is useful if every line of the file contains the same kind of information. my $line = $_. chomp($line). '>output. my $age =nlin. 111 .txt'). open (my $fh. 'input. print $fh "once\n". Another way to read from a filehandle is to assign the angle operator of the filehandle to a scalar. print "Name: $name.txt'). This is useful if you are reading a file where every line has a different meaning. } my $name=nlin. To make a little more useful. But it requires that you test the return value to make sure it is defined. you can wrap it up in a subroutine to hide the error checking.txt') or die "could not open".This script shows a cat -n style function. 18.4 write If the file is opened for write or append. my $num=0. open (my $fh. print $fh "a time\n". close $fh. use Carp. my $addr=nlin.

txt" because "~" only means something to the shell.5 File Tests Perl can perform tests on a file to glean information about the file.txt expression: my @textfiles = glob ("*. 112 .18. FILE is a filename (string) or filehandle. use glob(). All tests return a true (1) or false ("") value about the file. This is also useful to translate Linux style "~" home directories to a usable file path. For example. Some common tests include: -e -f -d -l -r -w -z -p -S -T file file file file file file file file file file exists is a plain file is a directory is a symbolic link is readable is writable size is zero is a named pipe is a socket is a text file (perl's definition) 18. Perl's open() function cannot open "~/list.txt"). my $startup_file = glob('~/. To translate to a real directory path. All the tests have the following syntax: -x FILE The "x" is a single character indicating the test to perform. The "~" in Linux is a shell feature that is translated to the user's real directory path under the hood. if you wish to get a list of all the files that end with a .6 File Globbing The glob() function takes a string expression and returns a list of files that match that expression using shell style filename expansion and translation.cshrc'). my @files = glob ( STRING_EXPRESSION ).

It is included in perl 5. If you process() was called on a file and not just a directory.txt$}) {print "found text file $fullname\n".. This process() subroutine prints out all . Your process() subroutine can read this variable and perform whatever testing it wants on the fullname. use File::Find. the path to the file is available in $File::Find::dir and the name of the file is in $_. if ($fullname =~ m{\.1. then find() will not recurse any further into the current directory. return..} if((-d $fullname) and ($fullname=~m{CVS})) {$File::Find::prune=1.18. The process() subroutine will be called on every file and directory in $pwd and recursively into every subdirectory and file below.6. chomp($pwd). including searches down an entire directory structure. sub process { .7 File Tree Searching For sophisticated searching. } The process() subroutine is a subroutine that you define. find(\&process. If your process() subroutine sets the package variable $File::Find::prune to 1.} } For more information: perldoc File::Find 113 .$pwd). my $pwd=`pwd`.txt files encountered and it avoids entering any CVS directories. sub process { my $fullname = $File::Find::name. The package variable $File::Find::name contains the name of the current file or directory. use the File::Find module.

If you call system() on the finger command. there is a third way to run system commands within your perl script. use the backtick operator. system($cmd)==0 or die "Error: could not '$cmd'". which means the user will see the output scroll by on the screen. you just want to know if it worked. 1. The system() function executes the command string in a shell and returns you the return code of the command. In Linux. all this text will go to STDOUT and will be seen by the user when they execute your script. but if you are doing system commands in perl and you are using Tk. you might do something like this: my $cmd = "rm -f junk. The module provides the user with a "Go/Cancel" button and allows the user to cancel the command in the middle of execution if it is taking too long. using the Tk::ExecuteCommand module. 19. If you type: linux> finger username Linux will dump a bunch of text to STDOUT. my $string_results = `finger username`.2 The Backtick Operator If you want to capture the STDOUT of a operating system command. then you will want to use the backtick operator.`command string`. a non-zero indicates some sort of error. 19. A simple example is the "finger" command on Linux. This is a very cool module that allows you to run system commands in the background as a separate process from you main perl script. 2. When you execute a command via the system() function. 114 .system("command string"). and then it is lost forever. We have not covered the GUI toolkit for perl (Tk). So to use the system() function and check the return value.1 The system() function If you want to execute some command and you do not care what the output looks like. a return value of ZERO is usually good.txt". the output of the command goes to STDOUT.19 Operating System Commands Two ways to issue operating system commands within your perl script are the system function and the backtick operator. 19.3 Operating System Commands in a GUI If your perl script is generating a GUI using the Tk package. then you will likely want to use the system() function. You can then process this in your perl script like any other string. you should look into Tk::ExecuteCommand. The $string_results variable will contain all the text that would have gone to STDOUT. If you want to capture what goes to STDOUT and manipulate it within your script.

's' for substitution.transliterate tr{OLD_CHAR_SET}{NEW_CHAR_SET} Perl allows any delimiter in these operators.20 Regular Expressions Regular expressions are the text processing workhorse of perl.=~ pattern does match string expression 2. adverbs. etc ). There are three different regular expression operators in perl: 1. 115 . such as {} or () or // or ## or just about any character you wish to use. There are two ways to "bind" these operators to a string expression: 1.!~ pattern does NOT match string expression Binding can be thought of as "Object Oriented Programming" for regular expressions. You may see perl code that simply looks like this: /patt/. Binding in Regular Expressions can be looked at in a similar fashion: $string =~ verb ( pattern ). With regular expressions. you can search strings for patterns.substitute s{OLDPATTERN}{NEWPATTERN} 3. Generic OOP structure can be represented as $subject -> verb ( adjectives. find out what matched the patterns. but I prefer to use m{} and s{}{} because they are clearer for me.match m{PATTERN} 2. The most common delimiter used is probably the m// and s/// delimiters. and 'tr' for translate. This is functionally equivalent to this: $_ =~ m/patt/. where "verb" is limited to 'm' for match. and substitute the matched patterns with new strings.

# simple encryption. print "$car\n". The above examples all look for fixed patterns within the string. decrypted: How I love thee. > My car is a Jaguar 116 . $love_letter =~ tr{A-Za-z}{N-ZA-Mn-za-m}. Regular expressions also allow you to look for patterns with different types of "wildcards". This allows the pattern to be contained within variables and interpolated during the regular expression. print $car. 20. if($email =~ m{Free Offer}) {$email="*deleted spam*\n". Caesar cypher my $love_letter = "How I love thee. my $car = "My car is a Toyota\n". # upgrade my car my $car = "my car is a toyota\n". $car =~ s{$actual}{$wanted}.1 Variable Interpolation The braces that surround the pattern act as double-quote marks. } print "$email\n". $love_letter =~ tr{A-Za-z}{N-ZA-Mn-za-m}. > > > > *deleted spam* my car is a jaguar encrypted: Ubj V ybir gurr. print "encrypted: $love_letter". $car =~ s{toyota}{jaguar}.\n". my $actual = "Toyota". my $wanted = "Jaguar".Here are some examples: # spam filter my $email = "This is a great Free Offer\n". print "decrypted: $love_letter\n". subjecting the pattern to one pass of variable interpolation as if the pattern were contained in double-quotes.

$size\n".1024 > input.20. the parenthesis were in the pattern but did not occur in the string.dat.txt size: 1024 filename: input.3 Defining a Pattern A pattern can be a literal pattern such as {Free Offer}. 117 . } } > output. yet the pattern matched. print "$name.db size: 1048576 MARKER . 0-9". each containing the pattern {filename: } followed by one or more non-whitespace characters forming the actual filename. my $size = $1.dat size: 512 filename: address. <<"MARKER" filename: output. my @lines = split "\n".txt. ########################### $line =~ m{size: (\d+)}.db.2 Wildcard Example In the example below.512 > address. # the "+" means "one or more" #################################### if($line =~ m{filename: (\S+)}) { my $name = $1.1048576 20. ########################### # \d is a wildcard meaning # "any digit. Notice in the above example. Each line also contains the pattern {size: } followed by one or more digits that indicate the actual size of that file. foreach my $line (@lines) { #################################### # \S is a wildcard meaning # "anything that is not white-space". It can contain wildcards such as {\d}. we process an array of lines. It can also contain metacharacters such as the parenthesis.

4 Metacharacters Metacharacters do not get interpreted as literal characters. match any single character in class * (quantifier): match previous item zero or more times + (quantifier): match previous item one or more times ? (quantifier): match previous item zero or one time { } (quantifier): match previous item a number of times in given range ^ (position marker): beginning of string (or possibly after "\n") $ (position marker): end of string (or possibly before "\n") 118 . If not a shortcut. \ (backslash) if next character combined with this backslash forms a character class shortcut. | alternation: (patt1 | patt2) means (patt1 OR patt2) ( ) (?: ) . then simply treat next character as a non-metacharacter. (somewhat faster) match any single character (usually not "\n") define a character class. The following are metacharacters in perl regular expression patterns: \ | ( ) [ ] { } ^ $ * + ? .20. [ ] grouping (clustering) and capturing grouping (clustering) only. then match that character class. Instead they tell perl to interpret the metacharacter (and sometimes the characters around metacharacter) in a different way. no capturing.

... matches end of string # match 'John' only if it occurs at end of string if($str =~ m{John$}){warn "dollar". John".} > > > > > > > alt at ...} # ? quantifier. Change the value assigned to $str and re-run the script.} # ^ position marker. match previous item zero or more # match '' or 'z' or 'zz' or 'zzz' or 'zzzzzzzz' if($str =~ m{z*}){warn "asterisk". match previous.. class at .} # {} quantifier.} # () grouping and capturing # match 'goodday' or 'goodbye' if($str =~ m{(good(day|bye))}) {warn "group matched.} # . # | alternation # match "hello" or "goodbye" if($str =~ m{hello|goodbye}){warn "alt". captured '$1'".5}ast}){warn "curly brace". " Sincerely. and 'fffffast' if($str =~ m{f{3. hello and goodday! " dogs and cats and sssnakes put me to sleep.. question at ." . previous item is optional # match only 'dog' and 'dogs' if($str =~ m{dogs?}){warn "question". captured 'goodday' at . any single character # match 'cat' 'cbt' 'cct' 'c%t' 'c+t' 'c?t' .. asterisk at .} # * quantifier. group matched. Hummingbirds are ffffast. my . 'ffffast'. matches beginning of string # match 'Dear' only if it occurs at start of string if($str =~ m{^Dear}){warn "caret"." ..} # $ position marker.} # + quantifier...t}){warn "period". match previous item one or more # match 'snake' 'ssnake' 'sssssssnake' if($str =~ m{s+nake}){warn "plus sign"..} # [] define a character class: 'a' or 'o' or 'u' # match 'cat' 'cot' 'cut' if($str =~ m{c[aou]t}){warn "class". period at .. plus sign at .. Experiment with what matches and what does not match the different regular expression patterns. 119 ." zzzz.Examples below. 3 <= qty <= 5 # match only 'fffast'." $str = "Dear sir. if($str =~ m{c...

$first $last\n".. multiplication has a higher precedence than addition. $3. … variables. Normally. . ############################################ # $1 $2 $test=~m{Firstname: (\w+) Lastname: (\w+)}. my $last = $2. captured '$1'". $2.} 120 .> curly brace at ... we want to cluster "day|bye" so that the alternation symbol "|" will go with "day" or "bye". 20. John Smith Because capturing takes a little extra time to store the captured result into the $1. The captured values are accessible through some "magical" variables called $1.1 $1. print "Hello. the pattern would match "goodday" or "bye". my $test="Firstname: John Lastname: Smith". The pattern contains capturing parens around the entire pattern. > dollar at . The left parenthesis are counted from left to right as they occur within the pattern.. $3. matching "cats" or null string. sometimes you just want to cluster without the overhead of capturing. The pattern {(cats)?} will apply the "?" quantifier to the entire pattern within the parentheses.5 Capturing and Clustering Parenthesis Normal parentheses will both cluster and capture the pattern they contain. Without the clustering parenthesis. 20. The pattern {cats?} will apply the "?" quantifier to the letter "s". > caret at . yielding the result of "20". yielding the result of "14". so we do not need to capture the "day|bye" part of the pattern. starting at 1. In the below example. matching either "cat" or "cats".5. rather than "goodday" or "goodbye". therefore we use cluster-only parentheses. etc Capturing parentheses Clustering parentheses will also Capture the part of the string that matched the pattern within parentheses.. if($str =~ m{(good(?:day|bye))}) {warn "group matched. The expression "(2 + 3) * 4" forces the addition to occur first.. $2. Clustering affects the order of evaluation similar to the way parentheses affect the order of evaluation within a mathematical expression. my $first = $1. > Hello.. $2.. The expression "2 + 3 * 4" does the multiplication first and then the addition. Each left parenthesis increments the number used to access the captured string. Clustering parentheses work in the same fashion.

Cluster-only parenthesis don't capture the enclosed pattern, and they don't count when determining
which magic variable, $1, $2, $3 ..., will contain the values from the
capturing parentheses.
my $test = 'goodday John';
##########################################
#
$1
$2
if($test =~ m{(good(?:day|bye)) (\w+)})
{ print "You said $1 to $2\n"; }
> You said goodday to John

20.5.2 Capturing parentheses not capturing
If a regular expression containing capturing parentheses does not match the string, the magic variables
$1, $2, $3, etc will retain whatever PREVIOUS value they had from any PREVIOUS regular
expression. This means that you MUST check to make sure the regular expression matches BEFORE
you use the $1, $2, $3, etc variables.
In the example below, the second regular expression does not match, therefore $1 retains its old value
of 'be'. Instead of printing out something like "Name is Horatio" or "Name is" and failing on an
undefined value, perl instead keeps the old value for $1 and prints "Name is 'be'", instead.
my $string1 = 'To be, or not to be';
$string1 =~ m{not to (\w+)}; # matches, $1='be'
warn "The question is to $1";
my $string2 = 'that is the question';
$string2 =~ m{I knew him once, (\w+)}; # no match
warn "Name is '$1'";
# no match, so $1 retains its old value 'be'
> The question is to be at ./script.pl line 7.
> Name is 'be' at ./script.pl line 11.

20.6 Character Classes
The "." metacharacter will match any single character. This is equivalent to a character class that
includes every possible character. You can easily define smaller character classes of your own using
the square brackets []. Whatever characters are listed within the square brackets are part of that
character class. Perl will then match any one character within that class.
[aeiouAEIOU] any vowel
[0123456789] any digit

121

20.6.1 Metacharacters Within Character Classes
Within the square brackets used to define a character class, all previously defined metacharacters cease
to act as metacharacters and are interpreted as simple literal characters. Characters classes have their
own special metacharacters.
\
(backslash) demeta the next character
-

(hyphen) Indicates a consecutive character range, inclusively.
[a-f] indicates the letters a,b,c,d,e,f.
Character ranges are based off of ASCII numeric values.

^

If it is the first character of the class, then this indicates the class
is any character EXCEPT the ones in the square brackets.
Warning: [^aeiou] means anything but a lower case vowel. This
is not the same as "any consonant". The class [^aeiou] will
match punctuation, numbers, and unicode characters.

20.7 Shortcut Character Classes
Perl has shortcut character classes for some more common classes.
shortcut

class

description

\d

[0-9]

any digit

\D

[^0-9]

any NON-digit

\s

[ \t\n\r\f]

any whitespace

\S

[^ \t\n\r\f]

any NON-whitespace

\w

[a-zA-Z0-9_]

any word character (valid perl identifier)

\W

[^a-zA-Z0-9_]

any NON-word character

122

20.8 Greedy (Maximal) Quantifiers
Quantifiers are used within regular expressions to indicate how many times the previous item occurs
within the pattern. By default, quantifiers are "greedy" or "maximal", meaning that they will match as
many characters as possible and still be true.
*

match zero or more times (match as much as possible)

+

match one or more times (match as much as possible)

?

match zero or one times (match as much as possible)

{count}

match exactly "count" times

{min, }

match at least "min" times (match as much as possible)

{min,max} match at least "min" and at most "max" times
(match as much as possible)

20.9 Thrifty (Minimal) Quantifiers
Placing a "?" after a quantifier disables greediness, making them "non-greedy", "thrifty", or "minimal"
quantifiers. Minimal quantifiers match as few characters as possible and still be true.
*?
match zero or more times
(match as little as possible and still be true)
+?

match one or more times
(match as little as possible and still be true)

{min,}?

match at least min times
(match as little as possible and still be true)

{min, max}?

match at least "min" and at most "max" times
(match as little as possible and still be true)

This example shows the difference between minimal and maximal quantifiers.
my $string = "12340000";
if($string =~ m{^(\d+)0+$})
{ print "greedy '$1'\n"; }
if($string =~ m{^(\d+?)0+$})
{ print "thrifty '$1'\n"; }
> greedy '1234000'
> thrifty '1234'

123

\Z Matches the end of the string only. the pattern before and after that anchor must occur within a certain position within the string. \b word "b"oundary A word boundary occurs in four places. Not affected by /m modifier. 1) at a transition from a \w character to a \W character 2) at a transition from a \W character to a \w character 3) at the beginning of the string 4) at the end of the string \B NOT \b \G usually used with /g modifier (probably want /c modifier too). unless($test2=~m{\bjump\b}) { print "test2 does not match\n".10. Indicates the position after the character of the last pattern match performed on the string.20. } my $test2='Pick up that jumprope. they translate into a "position" within the string. } > test1 matches > test2 does not match 124 .'.10 Position Assertions / Position Anchors Inside a regular expression pattern.1 The \b Anchor Use the \b anchor when you want to match a whole word pattern but not part of a word.'. If the /m (multiline) modifier is present. 20. Instead. If this is the first regular expression begin performed on the string then \G will match the beginning of the string. If the /m (multiline) modifier is present. but will chomp() a "\n" if that was the last character in string. Not affected by /m modifier. Use the pos() function to get and set the current \G position within the string. This example matches "jump" but not "jumprope": my $test1='He can jump very high. matches "\n" also. ^ Matches the beginning of the string. \z Match the end of string only. \A Match the beginning of string only. If a position anchor occurs within a pattern. $ Matches the end of the string. some symbols do not translate into a character or character class. if($test1=~m{\bjump\b}) { print "test1 matches\n". matches "\n" also.

The \G anchor represents the position within the string where the previous regular expression finished. The first time a regular expression is performed on a string. the \G anchor represents the beginning of the string.20. Without the "cg" modifiers. The "cg" modifiers tell perl to NOT reset the \G anchor to zero if the regular expression fails to match. The \G anchor is usually used with the "cg" modifiers.10. 125 . Assigning to pos($str) will change the position of the \G anchor for that string. The pos() function will return the character index in the string (index zero is to the left of the first character in the string) representing the location of the \G anchor. the first regular expression that fails to match will reset the \G anchor back to zero. using the \G anchor to indicate the location where the previous regular expression finished. This will allow a series of regular expressions to operate on a string. The location of the \G anchor within a string can be determined by calling the pos() function on the string.2 The \G Anchor The \G anchor is a sophisticated anchor used to perform a progression of many regular expression pattern matches on the same string.

the script prints the pos() value of the string."\n".pos($str). if($str=~m{\GFirstname: (\w+) }cg) { my $first = $1.The example below uses the \G anchor to extract bits of information from a single string."\n". 126 . resulting in a much slower script. } if($str=~m{\GLastname: (\w+) }cg) { my $last = $1. } $str=~m{\GBookcollection: }cg. } > > > > > > > > pos is 16 pos is 32 book is 'Programming Perl' pos is 65 book is 'Perl Cookbook' pos is 80 book is 'Impatient Perl' pos is 95 Another way to code the above script is to use substitution regular expressions and substitute each matched part with empty strings. After every regular expression.pos($str). while($str=~m{\G\s*([^. The problem is that a substitution creates a new string and copies the remaining characters to that string. print "pos is ". print "pos is ". Perl Cookbook.]+). but if you have a script that is parsing through a lot of text. the difference can be quite significant."\n". print "pos is ".?}cg) { print "book is '$1'\n". my $str = "Firstname: John Lastname: Smith Bookcollection: Programming Perl. Impatient Perl". Notice how the pos() value keeps increasing. In the above example.pos($str). the speed difference would not be noticeable to the user.

1 Global Modifiers The following modifiers can be used with m{}. ^ and $ position anchors will only match literal beginning and end of string. (DEFAULT) ". etc x ignore spaces and tabs and carriage returns in pattern. possible speed improvement. ".20. i case Insensitive. treating strings as a multiple lines. CAT.11." will NOT match "\n" ^ and $ position anchors will match literal beginning and end of string and also "\n" characters within the string. or tr{}{}. outside any curly braces." will match "\n" within the string. Cat. $str =~ tr{oldset}{newset}modifiers. m treat string as Multiple lines. CaT.2 The m And s Modifiers The default behavior of perl regular expressions is "m". ^ and $ indicate start/end of "line" instead of start/end of string. 127 . m{cat}i matches cat. This allows the pattern to be spread out over multiple lines and for regular perl comments to be inserted within the pattern but be ignored by the regular expression engine.11. ^ matches after "\n" $ matches before "\n" o compile the pattern Once. If neither a "m" or "s" modifier is used on a regular expression. $str =~ m{pattern}modifiers. Modifiers are placed after the regular expression. 20. 20. $str =~ s{oldpatt}{newpatt}modifiers. s{}{}.11 Modifiers Regular expressions can take optional modifiers that tell perl additional information about how to interpret the regular expression. perl will default to "m" behavior. s treat string as a Single line. CAt.

Notice in the "s" version. The only difference is the modifier used on the regular expression. even if the string is multiple lines with embedded "\n" characters. my $string = "Library: Programming Perl \n" . then the "^" anchor will only match the literal beginning of the string."Impatient Perl". the captured string includes the newline "\n" characters which shows up in the printed output. } if($string =~ m{Library: (. the "$" anchor will only match the literal end of string." character set will match any character EXCEPT "\n"."Perl Cookbook\n" . the "$" anchor will match the end of the string or any "\n" characters.*)}s) { print "singleline is '$1'\n". The single line version prints out the captured pattern across three different lines. then the default behavior (the "m" behavior) is to treat the string as multiple lines.*)}) { print "default is '$1'\n". if($string =~ m{Library: (. using "^" and "$" to indicate start and end of lines. } > > > > > default is 'Programming Perl ' multiline is 'Programming Perl ' singleline is 'Programming Perl Perl Cookbook Impatient Perl' 128 .If the "m" modifier is used. and the ". } if($string =~ m{Library: (. then the "^" anchor will match the beginning of the string or "\n" characters." class will match any character including "\n". If the "s" modifier is used. This example shows the exact same pattern bound to the exact same string.*)}m) { print "multiline is '$1'\n". the "s" modifier forces perl to treat it as a single line. If a string contains multiple lines separated by "\n". and the ". With the "s" modifier.

if( $string =~ m { ^ \s* ([-+]?) # positive or negative or optional \s* ( \d+ ) # integer portion ( \. Also. for easier reading. Without them.3 The x Modifier The x modifier allows a complex regular expression pattern to be spread out over multiple lines. with comments.11. "fraction is '$fraction'\n". my $string = '.20. "exponent is '$exponent'\n". my $integer = $2 || ''. Most whitespace within a pattern with the x modifier is ignored. The double-pipe expressions guarantee that the variables are assigned to whatever the pattern matched or empty string if no match occurred. my $exponent = $4 || ''. my $fraction = $3 || ''. } > > > > sign is '-' integer is '134' fraction is '. it must be explicitly stated using \s or \t or \n or some similar character class.23423' exponent is ' e -12' A couple of notes for the above example: The x modifier strips out all spaces. "integer is '$integer'\n". The following pattern is looking for a number that follows scientific notation.23423 e -12'. and carriage returns in the pattern. The pattern is spread out over multiple lines with comments to support maintainability. 129 . If the pattern expects whitespace in the string. with "^" or "$" or "\G". it's always a good idea to anchor your regular expression somewhere in your string. print print print print "sign is '$sign'\n". \d+ )? # fractional is optional ( \s* e \s* [+-]? \d+)? # exponent is optional }x ) { my $sign = $1 || ''. tabs.134. an unmatched pattern match will yield an "undef" in the $1 (or $2 or $3) variable associated with the match.

20.14 Modifiers for tr{}{} Operator The following modifiers apply to the tr{oldset}{newset} operator only. cg Continue search after Global search fails.12 Modifiers For m{} Operator The following modifiers apply to the m{pattern} operator only: g Globally find all matchs. Without this modifier. This maintains the \G marker at its last matched position. the result of the expression becomes the replacement string. 20. 20. returning a value that can be stored in a scalar for pattern matching at a later time. m{} will find the first occurrence of the pattern.13 Modifiers for s{}{} Operator The following modifiers apply to the s{oldpatt}{newpatt} operator only. check out the Regexp::Common module on CPAN. the \G marker is reset to zero if the pattern does not match. # remove perl comments next if($str =~ m{^\s*$}).\d+)?\s*(?:e\s*[+-]?\s*\d+)?}. 130 . c Complement the searchlist d Delete found but unreplaced characters s Squash duplicate replaced characters 20. my $number = qr{[+-]?\s*\d+(?:\.16 Common Patterns Some simple and common regular expression patterns are shown here: $str =~ s{\s}{}g. # remove all whitespace $str =~ s{#. Without this modifier. g Globally replace all occurrences of oldpatt with newpatt e interpret newpatt as a perl-based string Expression.15 The qr{} function The qr{} function takes a string and interprets it as a regular expression.# next if only whitespace For common but more complicated regular expressions.*}{}.20.

423E-42 the number". $str =~ m{($RE{num}{real})}. my $patt = $RE{num}{real}.}))?)(?: (?:[E])(?:(?:[+-]?)(?:[0123456789]+))|)) As complicated as this is. The hash lookup can be used directly within your regular expression: use Regexp::Common. it is a lot easier to reuse someone else's code than to try and reinvent your own. the data in the hash are the patterns to use within regular expressions. regular expression patterns (balanced parentheses and brackets. integers and floating point numbers of different bases. Here is how to find out what the floating point number pattern looks like in Regexp::Common: use Regexp::Common. print "$patt\n".20. it might be worth a moment to check out Regexp::Common and see if someone already did the work to match the pattern you need. email addresses. faulty. If you are doing some complicated pattern matching. cpan> install Regexp::Common Once Regexp::Common is installed. but fairly complicated.])(?:[0123456789]{0. > match is '-12. > (?:(?i)(?:[+-]?)(?:(?=[0123456789]|[. lopsided. and others).17 Regexp::Common The Regexp::Common module contains many common. wheel.423E-42' 131 . delimited text with escapes. perl scripts that use it will have a "magic" hash called %RE imported into their namespace. print "match is '$1'\n". The keys to this hash are human understandable names.])(?: [0123456789]*)(?:(?:[. my $str = "this is -12.

Parse::RecDescent uses regular expression styled patterns to define grammar rules. regular expressions may become a cumbersome means to extract the desired data. phonenumber. such as extracting information out of a tab separated database that is organized by lastname. ZIP. address. dateof-birth. The data is always in a fixed location. the Parse::RecDescent module may prove useful in that it allows whole gramatical rules to be defined. and a regular expression can be used to perform searches within that data. state. 132 . If the data being parsed is not quite so rigid in its definition. cpan> install Parse::RecDescent Parse::RecDescent describes itself as a module that incrementally generates top-down recursivedescent text parsers from simple yacc-like grammar specifications. and the module parses the data according to those rules. and these rules can be combined fairly easily to create complex rules. firstname.21 Parsing with Parse::RecDescent Perl's regular expression patterns are sufficient for many situations. In simpler terms. city. Instead.

> He's dead.} curse: 'Dammit' | 'Goddammit' name: 'Jim' | 'Spock' | 'Scotty' job: 'magician' | 'miracle worker' | 'perl hacker' pronoun: "He's" | "She's" | "It's" | "They're" }. not a magician!\n". Jim. I'm a doctor. } "dead. not a" job "!" "Just do what you can. while(<>) { $parse->McCoy($_). Jim. print "> ". } > > > > > > > > > > > > try typing these lines: He's dead. Jim. Bones. I'm a doctor." name "!" "Shut up. not a magician! Just do what you can. print "try typing these lines:\n". Jim! Dammit. print "Dammit. print "press <CTL><D> when finished\n". Jim! Shut up. Bones. Jim!\n". print "> ". > You green blooded Vulcan! ERROR (line 1): Invalid McCoy: Was expecting curse. my $grammar McCoy: curse ".\n". print "He's dead. I'm a doctor.\n". or pronoun 133 ." { print | pronoun { print | <error> = q{ name ". my $parse = new Parse::RecDescent($grammar).Here is a quick example from perldoc Parse::RecDescent use Parse::RecDescent. Bones. Bones. I'm a doctor. not a magician! press <CTL><D> when finished > Dammit.

and normal regular expressions are becoming difficult to manage. And Parse::RecDescent has an additional learning curve above and beyond perl's regular expressions. so you need to learn basic regular expression patterns before you use Parse::RecDescent. the more rules. Since it recursively descends through its set of rules. then Parse::RecDescent would be the next logical module to look at. If the data you are mining is fairly complex. 134 .Parse::RecDescent is not the solution for every pattern matching problem. Parse::RecDescent is slower than simple regular expressions. Parse::RecDescent currently must read in the entire text being parsed. which can be a problem if you are parsing a gigabyte-sized file. the longer it takes to run. Parse::RecDescent uses perl"s regular expression patterns in its pattern matching.

drawing the GUI. the Tk module has a widget demonstration program that can be run from the command line to see what widgets are available and what they look like. Perl has a Graphical User Interface (GUI) toolkit module available on CPAN called Tk. MainLoop. When the above example is executed. The MainLoop is a subroutine call that invokes the event loop.22 Perl. responding to button clicks. my $top=new MainWindow. a small GUI will popup on the screen (the MainWindow item) with a button (the $top->Button call) labeled "Hello" (the -text option). Several large books have been written about the Tk GUI toolkit for perl. -command=>sub{print "Hi\n". Once installed.} )->grid(-row=>1. User input and output occurred through the same command line used to execute the perl script itself. When the mouse left-clicks on the button. > widget Here is a simple "hello world" style program using Tk: use Tk. 135 . I recommend the "Mastering Perl/Tk" book. the word "Hi" is printed to the command line (the -command option). the widget will not show up in the GUI). At the command line. GUI. cpan> install Tk The Tk module is a GUI toolkit that contains a plethora of buttons and labels and entry items and other widgets needed to create a graphical user interface to your scripts. all the examples have had a command line interface. and Tk So far. type "widget" to run the demonstration program. The ->grid method invokes the geometry manager on the widget and places it somewhere in the GUI (without geometry management.-column=>1). If you plan on creating GUI's in your scripts. And it would be impossible to give any decent introduction to this module in a page or two. $top->Button ( -text=>"Hello". etc.

3 November 2008 Copyright (C) 2000. We have designed this License in order to use it for manuals for free software. But this License is not limited to software manuals. textbook. You accept the license if you copy. but changing it is not allowed. It complements the GNU General Public License. A "Secondary Section" is a named appendix or the Document that deals exclusively with the publishers or authors of the Document to the subject (or to related matters) and contains 136 a front-matter section of relationship of the Document's overall nothing that could fall . either copied verbatim. modify or distribute the work in a way requiring permission under copyright law. with or without modifying it. 2001. We recommend this License principally for works whose purpose is instruction or reference. 2002. 0. that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. it can be used for any textual work. and is addressed as "you".23 GNU Free Documentation License GNU Free Documentation License Version 1. 2007. or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it. to use that work under the conditions stated herein. while not being considered responsible for modifications made by others. below. unlimited in duration.org/> Everyone is permitted to copy and distribute verbatim copies of this license document. The "Document". APPLICABILITY AND DEFINITIONS This License applies to any manual or other work. refers to any such manual or work. Secondarily. or with modifications and/or translated into another language. PREAMBLE The purpose of this License is to make a manual. This License is a kind of "copyleft". 2008 Free Software Foundation.3. <http://fsf. royalty-free license. because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. 1. A "Modified Version" of the Document means any work containing the Document or a portion of it. regardless of subject matter or whether it is published as a printed book. in any medium. Such a notice grants a world-wide. which is a copyleft license designed for free software. which means that derivative works of the document must themselves be free in the same sense. either commercially or noncommercially. Any member of the public is a licensee. this License preserves for the author and publisher a way to get credit for their work. Inc.

A copy that is not "Transparent" is called "Opaque". LaTeX input format. the material this License requires to appear in the title page. and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors. PostScript or PDF designed for human modification. The Document may contain zero Invariant Sections. represented in a format whose specification is available to the general public. Examples of transparent image formats include PNG. ethical or political position regarding them. plus such following pages as are needed to hold. in the notice that says that the Document is released under this License. that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor. for a printed book. If the Document does not identify any Invariant Sections then there are none. "Title Page" means the text near the most prominent appearance of the work's title. The "publisher" means any person or entity that distributes copies of the Document to the public. XCF and JPG. the title page itself. (Here XYZ stands for a 137 . SGML or XML using a publicly available DTD. legibly. as Front-Cover Texts or Back-Cover Texts. and standard-conforming simple HTML. (Thus. Examples of suitable formats for Transparent copies include plain ASCII without markup. SGML or XML for which the DTD and/or processing tools are not generally available. preceding the beginning of the body of the text. An image format is not Transparent if used for any substantial amount of text. commercial. For works in formats which do not have any title page as such. A "Transparent" copy of the Document means a machine-readable copy. or of legal. The "Invariant Sections" are certain Secondary Sections whose titles are designated. A Front-Cover Text may be at most 5 words. philosophical. as being those of Invariant Sections. The "Title Page" means. A copy made in an otherwise Transparent file format whose markup. and a Back-Cover Text may be at most 25 words.) The relationship could be a matter of historical connection with the subject or with related matters. The "Cover Texts" are certain short passages of text that are listed.directly within that overall subject. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. if the Document is in part a textbook of mathematics. Texinfo input format. a Secondary Section may not explain any mathematics. or absence of markup. in the notice that says that the Document is released under this License. has been arranged to thwart or discourage subsequent modification by readers is not Transparent. and the machine-generated HTML. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. PostScript or PDF produced by some word processors for output purposes only.

free of added material. either commercially or noncommercially. can be treated as verbatim copying in other respects. "Dedications". numbering more than 100. or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document. you may accept compensation in exchange for copies. to ensure that this Transparent copy will remain thus accessible at the stated 138 . Both covers must also clearly and legibly identify you as the publisher of these copies. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. "Endorsements". under the same conditions stated above. and continue the rest onto adjacent pages. VERBATIM COPYING You may copy and distribute the Document in any medium. 2. If you use the latter option. you should put the first ones listed (as many as fit reasonably) on the actual cover. clearly and legibly. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. or "History". when you begin distribution of Opaque copies in quantity. all these Cover Texts: Front-Cover Texts on the front cover. you must take reasonably prudent steps. but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. such as "Acknowledgements". COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document. If you distribute a large enough number of copies you must also follow the conditions in section 3.) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.specific section name mentioned below. You may also lend copies. If you publish or distribute Opaque copies of the Document numbering more than 100. and Back-Cover Texts on the back cover. you must enclose the copies in covers that carry. and that you add no other conditions whatsoever to those of this License. These Warranty Disclaimers are considered to be included by reference in this License. The front cover must present the full title with all words of the title equally prominent and visible. However. and you may publicly display copies. as long as they preserve the title of the Document and satisfy these conditions. and the license notice saying this License applies to the Document are reproduced in all copies. the copyright notices. and the Document's license notice requires Cover Texts. If the required texts for either cover are too voluminous to fit legibly. 3. Copying with changes limited to the covers. provided that this License. you must either include a machine-readable Transparent copy along with each Opaque copy. You may add other material on the covers in addition.

in the form shown in the Addendum below. then add an item describing the Modified Version as stated in the previous sentence. you must do these things in the Modified Version: A. These may be placed in the "History" section. create one stating the title. Preserve all the copyright notices of the Document. if it has fewer than five). List on the Title Page. and preserve in the section all the substance and tone of each of the contributor acknowledgements 139 . immediately after the copyright notices. and from those of previous versions (which should. You may omit a network location for a work that was published at least four years before the Document itself. with the Modified Version filling the role of the Document. provided that you release the Modified Version under precisely this License. unless they release you from this requirement. Include. Preserve its Title. but not required. and add to it an item stating at least the title. D. If there is no section Entitled "History" in the Document. Preserve the network location. together with at least five of the principal authors of the Document (all of its principal authors. thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. 4. Use in the Title Page (and on the covers. and likewise the network locations given in the Document for previous versions it was based on. E. year. I. C. and publisher of the Document as given on its Title Page. Include an unaltered copy of this License. It is requested. K. You may use the same title as a previous version if the original publisher of that version gives permission.location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. to give them a chance to provide you with an updated version of the Document. authors. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. if there were any. and publisher of the Modified Version as given on the Title Page. In addition. H. as the publisher. For any section Entitled "Acknowledgements" or "Dedications". a license notice giving the public permission to use the Modified Version under the terms of this License. State on the Title page the name of the publisher of the Modified Version. if any) a title distinct from that of the Document. J. if any. as authors. or if the original publisher of the version it refers to gives permission. new authors. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above. given in the Document for public access to a Transparent copy of the Document. year. G. one or more persons or entities responsible for authorship of the modifications in the Modified Version. that you contact the authors of the Document well before redistributing any large number of copies. B. Preserve the Title of the section. be listed in the History section of the Document). Preserve the section Entitled "History". F.

you may at your option designate some or all of these sections as invariant. under the terms defined in section 4 above for modified versions. M. but you may replace the old one. statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. unmodified. provided it contains nothing but endorsements of your Modified Version by various parties--for example. you must combine any sections Entitled "History" 140 . If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document. To do this. and that you preserve all their Warranty Disclaimers. These titles must be distinct from any other section titles. you may not add another. and list them all as Invariant Sections of your combined work in its license notice. make the title of each such section unique by adding at the end of it. or else a unique number. If the Document already includes a cover text for the same cover. N. 5. Section numbers or the equivalent are not considered part of the section titles. and multiple identical Invariant Sections may be replaced with a single copy. and a passage of up to 25 words as a Back-Cover Text. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. on explicit permission from the previous publisher that added the old one. previously added by you or by arrangement made by the same entity you are acting on behalf of. Delete any section Entitled "Endorsements". L. You may add a passage of up to five words as a Front-Cover Text. The combined work need only contain one copy of this License. provided that you include in the combination all of the Invariant Sections of all of the original documents. to the end of the list of Cover Texts in the Modified Version. Preserve all the Invariant Sections of the Document. add their titles to the list of Invariant Sections in the Modified Version's license notice. in parentheses.and/or dedications given therein. In the combination. unaltered in their text and in their titles. COMBINING DOCUMENTS You may combine the Document with other documents released under this License. Such a section may not be included in the Modified Version. You may add a section Entitled "Endorsements". Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. If there are multiple Invariant Sections with the same name but different contents. Preserve any Warranty Disclaimers. the name of the original author or publisher of that section if known. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. O.

Otherwise they must appear on printed covers that bracket the whole aggregate. provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. provided that you also include the original English version of this License and the original versions of those notices and disclaimers. and all the license notices in the Document. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works. the original version will prevail. so you may distribute translations of the Document under the terms of section 4. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer. in or on a volume of a storage or distribution medium. and replace the individual copies of this License in the various documents with a single copy that is included in the collection. but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. then if the Document is less than one half of the entire aggregate. When the Document is included in an aggregate. and distribute it individually under this License. is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. You may include a translation of this License. If the Cover Text requirement of section 3 is applicable to these copies of the Document.in the various original documents. forming one section Entitled "History". TRANSLATION Translation is considered a kind of modification. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License. 8. provided you insert a copy of this License into the extracted document. 6. You may extract a single document from such a collection. You must delete all sections Entitled "Endorsements". 7. 141 . the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate. and follow this License in all other respects regarding verbatim copying of that document. likewise combine any sections Entitled "Acknowledgements". and any sections Entitled "Dedications". and any Warranty Disclaimers. or the electronic equivalent of covers if the Document is in electronic form. Replacing Invariant Sections with translations requires special permission from their copyright holders.

9. receipt of a copy of some or all of the same material does not give you any rights to use it. or distribute it is void. If your rights have been terminated and not permanently reinstated.gnu.org/copyleft/. and will automatically terminate your rights under this License. Moreover. or "History". your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means. modify. 10. However. sublicense. 11. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new. you may choose any version ever published (not as a draft) by the Free Software Foundation. or distribute the Document except as expressly provided under this License. sublicense. you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License.If a section in the Document is Entitled "Acknowledgements". Such new versions will be similar in spirit to the present version. then your license from a particular copyright holder is reinstated (a) provisionally. the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. "Dedications". Any attempt otherwise to copy. RELICENSING 142 . If the Document does not specify a version number of this License. and you cure the violation prior to 30 days after your receipt of the notice. that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. modify. this is the first time you have received notice of violation of this License (for any work) from that copyright holder. unless and until the copyright holder explicitly and finally terminates your license. See http://www. and (b) permanently. If the Document specifies that a particular numbered version of this License "or any later version" applies to it. Each version of the License is given a distinguishing version number. but may differ in detail to address new problems or concerns. TERMINATION You may not copy. If the Document specifies that a proxy can decide which future versions of this License can be used. if you cease all violation of this License. revised versions of the GNU Free Documentation License from time to time.

0 license published by Creative Commons Corporation. A copy of the license is included in the section entitled "GNU Free Documentation License". ADDENDUM: How to use this License for your documents To use this License in a document you have written.Texts. no Front-Cover Texts. If you have Invariant Sections. as well as future copyleft versions of that license published by that same organization. and no Back-Cover Texts.3 or any later version published by the Free Software Foundation. 2009. 143 . distribute and/or modify this document under the terms of the GNU Free Documentation License.. "Incorporate" means to publish or republish a Document. with no Invariant Sections. we recommend releasing these examples in parallel under your choice of free software license. If your document contains nontrivial examples of program code. and with the Back-Cover Texts being LIST. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1. and if all works that were first published under this License somewhere other than this MMC. in whole or in part. and (2) were thus incorporated prior to November 1. provided the MMC is eligible for relicensing." line with this: with the Invariant Sections being LIST THEIR TITLES. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3. to permit their use in free software. An MMC is "eligible for relicensing" if it is licensed under this License. and subsequently incorporated in whole or in part into the MMC. replace the "with. or some other combination of the three.. (1) had no cover texts or invariant sections."Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. Front-Cover Texts and Back-Cover Texts. as part of another Document. include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (c) YEAR YOUR NAME. a not-for-profit corporation with a principal place of business in San Francisco. merge those two alternatives to suit the situation. California. Permission is granted to copy. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. A public wiki that anybody can edit is an example of such a server. If you have Invariant Sections without Cover Texts. Version 1. such as the GNU General Public License. 2008. with the Front-Cover Texts being LIST.

.........110 closures.............................................................88 Capturing and Clustering Parenthesis..........................................................................................................................................32 @..21 BEGIN........................................................................................................................................................................................................................................................................................................................................................................................................................................................................23 caller........107 @ARGV.............................................76 complex data structures............................................................................................................................................................................................................................................................25 comparison operator...................................13 class..................................................................................................................................................................................................................................................................................98 bless REFERENCE..............................................................................................................................................................................................................................................................................71 code reuse.....................13 conditional operator....................................25 compiling............................................................................................................................................................................................................................................................ STRING.....................................54 backtick..............................................................................................................................................89 boolean.........................121 CHECK...........Alphabetical Index abs........25 code reference...........................................................................................................................................................105 Command Line Arguments...................51 anonymous subroutine....................................59 control flow...............53 concatenation...............................................................................................................32 $....................................................................................................28 continue................................................................................................................................................................................................................................................................................................................................................................................. Getopt::Declare.....................120 Character Classes.76 chomp.......................................32 Autovivification..................................................................................................................................................................................56 close.........................................83p........................................................................................................................................................76 bless......16 AND............................................................................................................59 144 .........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................66 cmp......................................................................................26 anonymous............................................................................................................................................................................................70 anonymous subroutines..........................................................................................................................................................................83 blessed invocant..................................................................78 command line......................................................................................................................................114 base conversion.......................................................................... bless / constructors...........................................................................................................................................................................................................................................................................................................................................................................74 can..............................................................................................................................94 clone...................................................................................................................................................................................................................................................................................................................................................................69 argument passing.....................................................................................104 comparison .....................................70 array................................................................................................................................................................

..........................................................................................................................................................................................................................................................................................................................22 delete.............................. file glob............................................59 END................................................................................................................................................................................................................................................................................................................................................................................................................. close...................................................................................................................................................cos............................................................................................56 dclone....................................42 dereference.............................................................................................................................................................................................................................................................................................112 -S...................... The Perl Module..........................................................................................................................................25 execution timeline................................................................................................................................................................................ 59 145 .............................110 open.............................................................................................................................................................................................. The Web Site.........................................................................................................................................103 Data Persistence.........................................................................................................12 e...............36.......112 -w.........................................................................................................................................................................................................71 double quote...................................................................................................................................................................................................................................................................................................................................100 CPAN........................................82 exists...................................111 File Test.........................................59 foreach............................................................................................................................................................112 -z..............................................................................................................................................112 -r.................................................17 CPAN.........................................................................................................................................................................................................................................110 write..................112 -f..............................................................113 for.......................112 -l............76 eq................................100 CPAN........................................................................................112 -T.........................................................................................................................................................................................................................................................................................................................................................................................................................112 File Tests..............................................................................................................................................................................................................................................56 defined........................................................................................................................................................................................112 File Input and Output..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................100 Creating Modules........43 else...............................................56 deep clone............................23p..........................................................................25 equal to...............................................................................................................................112 File::Find..41 exp.............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................. -d....................................................................................................................18 each........................................................................................................................................................................................................................................................................................................................................................59 elsif........................................................................................17 false......................................................112 -p.......................50 dereferencing code references...............................112 -e.............................................................................................................................................110 read....110 File IO......................18 exponentiation................................

................................................................................................................ ge...................76 int..........................................14 keys...........127 greater than...........................................................................................................................88 isa..47 literal.......................................................88 join................................................................18 log_x_base_b......................................................127 Global Modifiers (regular expressions).135 h2xs....................................25 less than or equal to .....................................................................................................................................................................................................................................................................................................25 greater than or equal to.......................................................................16 hexadecimal.......................................................................60 last.......88 INVOCANT->isa(BASEPACKAGE).................................................................................................................................................................................................................................................................................................................................................................................................... binary.................21 hexadecimal............................................................................................................................................................................................................................63 lexical variable................................................................16 if.....................................................................................................42 label.............................................................................................................................................................................................................................................................................................................................................................................................................................................13 less than................................................................................................................................................................................................................................................................................................................................................................................................................. 99 INIT...................................................................................................................................................................................................................garbage collection...................................................................12 local........................................................................................................................................................................................................25 lexical scope..................................................................................................................................................................................................................................................................................16 octal...............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................25 Getopt::Declare...................................................................................................86.......................60 le..............................................................................................................................................................................................................................16 string...............................................................................112 Global Modifiers..................................103 hash........................................25 GUI and Perl::Tk.............63 list.............................................................................................85 INVOCANT->can(METHODNAME)........................................................................................................................................................................................................................ Inheritance...........................................................................................................................................................59 imaginary numbers..................................................39 $..................40 here document....................................................................................................................................................................................68 log...................79pp.............................................................................................................................................................................................................................................................................123 gt...................................................................................................107 glob................................17 import............................................................25 length................................................................................................................................................................................................................................................................16 interpreting............................................................................................15 hex........................................................25 Greedy (Maximal) Quantifiers................................................................................................................................................18 146 ................................76 INVOCANT -> METHOD.....................................................................................................................................................64p................................................................................................................................

............................................................................................................................................................................................99 package.............................................................................................................................................................................................................................................................................................85 Methods..........................................26 lt.........................................................................................................17 Math::Trig...........................................................................83 Object Oriented Perl.................................................................................................80 147 .........................................................................................................................................................................................................................................98 oct..................16 rounding.........................................................................................115 Math::Complex................................................................................................................................................69 namespace.................................................................................................................................69 named subroutines........................................................................................................................................................................................................................................................................................................................................61 package qualified variable ....................................................................................16 open.............................................................55 multiline string.........................................................................................................................110 Operating System Commands...............61 natural logarithms......99 Modules............................60 NOT..............................................................................................................................................................................................................................................17 Metacharacters Within Character Classes.............................................................................................................................................................................................................................................17 numify..................................................25 nstore........................................................................18 ne......................................................................................................132 perl modules..............................................................................................................................114 system.........25 m/patt/................................................................................................................................................................................................................................61 package main......................................................................................................................................................................................................................................122 method calls...............................................................................................98 multidimensional array..........56 numbers..........62 Overriding Methods .....................................................................................................................................................................................................................78 PERL5LIB.....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................logical operators.....................25 next................................................50 named subroutine................................................................................................................................................114 `.................................................................................................................................................................................15 named referent.............................................................................................................................................................................................................................................................................................................................................................................................26 not equal to.......................................................................................61 Parse::RecDescent..................................................26 our.........................................20 Object Destruction.....................................................................................................................................................................................................................................................................................................................................................................................................................114 Tk::ExecuteCommand................................................................................................................................................................................................................................... literal............................................................................................................................................................................................................................................21 octal...........................................114 backtick...............................................................................114 OR...........................................................16 numeric...............................................................................97 object oriented perl................................................................................90 Object Oriented Review............................................................

............................................................................................... doube........................................................................................................................................................................................................................................................................18 read........................................................................................124 quantifier..............................................................................................................................................................................................................................118 m/patt/...............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................18 random numbers..........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................127 Greedy (Maximal) Quantifiers...............................................117 !~...................................................................121 clustering.............................................................................................................................................................................................................................................................................................................................................................................115 a character class...............................................................................................................117 Global Modifiers...............................115 =~..................................................................................................................................... $3................................60 ref..............................122 Thrifty (Minimal) Quantifiers..........................................................................118 alternation.....................118 Capturing and Clustering Parenthesis......56 return.....................................................................................120 repetition.............................................................................................................................................................................................................................................................perldoc....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................131 Regular Expressions............34 Position Assertions / Position Anchors............................................13 require..............................................................................................................................................................................57...........110 redo........................................................................ 84 reference............................................................................... retrieve................................................................. 84 Regexp::Common......................118 Position Assertions / Position Anchors.....73 reuse.............................................................................. 15 rand......................................................................................115 $1......................118 Shortcut Character Classes.............................................................................120 Character Classes..................................................................................................................................................................................................................................................................................................................................................................103 POD......................................................................................12 single.....79p....................115 Metacharacters....................................................................................................................................................................................................................................34 quote...............................................................................................................................12..................................................................103 Polymorphism.................................................................................49.......................118 Defining a Pattern............123 grouping.....................116 Wildcard Example.......78 reverse........................................................49 referent....................................94 pop.............................................................................................. $2.123 Variable Interpolation............................103 Plain Old Documentation.......................................................................................................................118 capturing..........................................................124 push..................................................................12 qw...38 148 ...............................................

................................................17 srand............................................................................................................................................................................................................................................................rounding....................................14 sprintf..........37 spaceship operator.......................................................................................................................................................................................................................................................35 Shortcut Character Classes.......................................................................13 SUPER................................................................................................................................................................................................16 string.............................................19 subroutine.................................................................................................................................................................................................................................................................................12 stringify...............................................................................................................................................................................................................................................69 substr..................................................................................................................................................................................................pm.............................................123 Tk::ExecuteCommand..............................................................................................................................................................................11....................................... argument passing........................................................................................................................................................................................................................................................................................................56 string...............................................................................................................................................................................................114 ternary operator.................................................................................................................................. double quote..............................................................................................17 trinary operator...................................................................................................35 use...........................................................................................................................................................................................................................................................................................................................17 scalar..87 use lib..................................28 true..........................18 Storable...39 split...................................................................................................................................................................................................................................22 unless.....................................................69 anonymous......................78 use base MODULENAME...........................................................................................59 unshift..............................122 sin.........................................................................................................23p...........................................................................................................................................................................12 sort.........................................................114 trigonometry.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................80 use Module......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................12 single quote................................................................66 named..............70 subroutine closures.................................................................11 shift.................................................................................................................................................................................................................................................................17 single quote.....................................................12 numbers................................................................. 33 Autovivify.............................95 system..................................................................................................................................................................................................................69 closures...........................................................................................................................................99 SUPER::..........98 149 ..................................................................................................................................................................................................................28 Thrifty (Minimal) Quantifiers...............................................................................................................................................................25 splice............................19 sqrt...............................................................................................................................................................................................................................................................................................................................................................................................................................66 subroutine return value.................................................73 subroutines........................................................................................................................ undefined...................................12 $..........................................

............................................26 $....................................................................................................................................112 -x......................................................................................................................................................................................................................................................26 XOR..........................................................................................................................................................................................................................................................................................................................................................111 ==.112 -z..............................................................................................................................................................................................................use MODULENAME...........................................25 <=>.......79 values..................................................................................................................................................................79 @ISA............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................59 write...............................................................................................................................................................................................................................................................................................................................................................................................25 ||.....................................................25 =~............25 <$fh>.................................................................................................................................................................................................................................................................................................................................................................43 wantarray....28 '...............................................112 -e........................11 150 ...............................................................................................26 !=...............................125 &&................................................................................................................................................................................................112 -S.................25 !~...................................115 >.........................................................................................................................112 -p.........................................................................................................................................................................................................................................................................124 \G..............28 !...............................................................................................................12 []..................................................................................................................................................................................................................................................................................................................................................................................................................................................................111 xor...........................................25 >=.............................................................................................................112 -f...................................................................................121 @.......................................................................................................................................................................................................................25 <<................................................................................................................17 \b...................................................................................................112 -T..............................11 scalar................................................................................................................................................................................................................................................................................................71 @ARGV.................................................................105 @INC..........................................26 <....................................................................................................................115 ?..................................................................................................................................................................112 -l...........................................................................................................................................................................................................................................................................12 ".........................................................................................................................................................................................................................................87 **...................................................................................................................................................................................112 -r.....................................................................................................112 :......................................................................................................................................26 -d.....................................................................................................................75 while........................................................................................15 <=...................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................32 @_.......................................................................................................................................................................112 -w.

.........$1..........120 The End......... 151 ................................................................................................... $2...... $3...............

Sign up to vote on this title
UsefulNot useful