You are on page 1of 24

Perl Tutorial

based on a tutorial by Nano Gough http://www.computing.dcu.ie/~ngough/perl/tutorial.ppt

Why Perl?
Perl is Pathologically Eclectic Rubbish Lister the duct tape of the internet the good at te%t processing rapid de&elopment fle%ibility operating system stuff in particular "N#$/L#N"$ wiss!army chain saw of "N#$ bad at numeric processing debugging efficiency

code re!use 'P(N:large repository of re!usable modules

The Three Virtues of a Good Programmer


(not necessarily of a good Student)
L()#NE : *he +uality that ma,es you go to great effort to reduce o&erall energy e%penditure. ma,es you want to re!use other people-s code #.P(*#EN'E: *he anger you feel when the computer is being la/y. ma,es you get things done +uic,ly 0rapid prototyping1 and efficiently 0optimi/e code1 2"3R# : E%cessi&e pride. ma,es you want to show off 0code sharing1 and write 0and maintain1 programs that other people won-t want to say bad things about.

Running Perl 45/usr/local/bin/perl 0tells the file to run through perl1


"se .pl e%tension Perl programName (to run the program) Perl !d programName (to run using debugger) Perl 6 w programName (to run with warnings)

Printing
4*he hash symbol 041 is use to comment lines of code 7 E&ery statement in perl ends with a semi!colon 071 Print 82ello 9orld. # lo&e perl.:7 4prints: 2ello 9orld. # lo&e perl. Print 82ello 9orld;n# lo&e perl;n:7 4prints: 2ello 9orld. # lo&e perl.

Scalar Variables
Examples: <name = >mary?7 <age = @A7

scalars store a single &alue regardless of type 0there are no types1 scalar &ariables always start with a -<Operations and Assignment

0B multiplication1 0; di&ision1 0! subtraction1 <a = C D @7 4 (dd C and @ and store in <a <a = E F @7 4 Remainder of E di&ided by @ DD<a7 4 #ncrement <a and then return it <aDD7 4 Return <a and then increment it !!<a7 4 Gecrement <a and then return it <a!!7 4 Return <a and then decrement it

Operations and Assignment contd..


<a = E7 <b=A7 <a = <b7 4 (ssign <b to <a 0<a=A1 <a D= <b7 or <a=<aDb7 4 (dd <b to <a 0<a=C@1 <a != <b7 or <a=<a!<b7 4 Concatenation <a = -.onday-7 <b=-*uesday-7 <c=<a . - - . <b7 <c= -.onday *uesday-7 <d= <a . - and - . <b7 <d=>.onday and *uesday?7 ubtract <b from <a 0<a=!@1 Interpolation 4 double +uotations may include &ars <c= 8<a <b:7 4 c is now -.onday *uesday-7 <d= 8<a and <b:7 4 <d is now -.onday and *uesday-7

Testing
Numbers <a == <b 4 #s <a numerically e+ual to <bH 4 don?t use <a=<b as this will not compare but Iust assign <b to <a <a 5= <b 4 #s <a numerically une+ual to <bH <aJ<b / <aK<b 4 #s <a less than/greater than <b <a J=<b / <a K=<b 4 #s a less than or e+ual to/ g.t or e+ to <b Strings <a e+ <b 4 #s <a string!e+ual to <bH <a ne <b 4 #s <a string!une+ual to <bH 4Lou can also use logical andM or and not: 0<a NN <b1 4 #s <a and <b trueH 0<a OO <b1 4 #s either <a or <b trueH 50<a1 *here are no 3oolean &alues false are the empty string - the number P undefined &alue undef empty list e&erything else is true

Conditionals
4if <a is e+ual red print the colour is red #f0<a e+ >red?1 Q print 8the colour is <a;n:7R 4in any other case 0if <a not e+ual to red1 print <a is not red else Q print 8*he colour <a is not red;n:7R 44444444444444444444444444444444444444 4if <a is e+ual to C M add @ to <a #f0<a ==C1Q <a = <aD@7R 4elsif <a is e+ual to @M add S to <a elsif 0<a ==@1 Q<a =<aDS7R 4in any other case add C to <a else Q <aDD7R

444444444444444444444444444444444
4if <a is e+ual to C (NG <b is e+ual to red: print 'olour C is red #f00<a==C1 OO 0<b e+ >red?11Qprint 8'olour <a is <b;n:7R

Arra s Initiali!e an arra "set to null Tcolours=017 #unctions push and pop 4assign elements to array Tcolours Tcolours=08red:M:blue:M:yellow:17 4use push function to add an element to the end of array push0TcoloursM:green:17 4colours now contains: 8red:M:blue:M:yellow:M:green: 4use pop function to remo&e an element from the end of array pop0Tcolours17 4colours now contains 8red:M 8blue:M 8yellow:

$#unctions shift and unshift Tcolours=08red:M:blue:M:yellow:17 <newUel=8green:7 4use unshift to append <newUel to start of array unshift0TcoloursM <newUel17 @colours is now: green,red,blue,yellow 4use shift to remo&e an element from the front of array shift0Tcolours17 Tcolours is now: 8red:M:blue:M:yellow:

Accessing an element o% t&e arra Tcolours = 08red:M:blue:M:yellow:17 print 8<coloursVPW:7 4prints: red

4 <4colours points to inde% of last element of array Tcolours

print 8<coloursV<4coloursW7 4prints: yellow


print Tcolours7 print 8Tcolours:7 4prints: redblueyellow 4print: red blue yellow

<colours = XTcoloursX7 4assigns colours to string print <colours7 4prints: red blue yellow

'oops
4Loops can be used to iterate through elements of an array #oreac& 'oop foreach <el 0Tcolours1 Q print 8*he colour is : <el;n:7 R 4*he foreach loop iterates through the array element by 4element. #n 4the first iteration $el is assigned the &alue of the first element of 4colours 0ie7 red1 etc.. 4*he result of e%ecuting this foreach statement is: *he colour is : red *he colour is : blue *he colour is : yellow

'oops contd(
#or 'oop for0<i=P7 <i J= <4colours7 <iDD1 Q print 8*he colour is : <coloursV<iW;n:7 R )&ile 'oop <i=P7 while0<i J= <4colours1 Q print 8<coloursV<iW;n:7 <iDD7 R E%planation:
#n a 8scalar conte%t: 0whene&er the parser e%pects a scalar1 an array is interpreted as the number of elements contained in it

'an also be written as: <i J Tcolours

Split
$split is a use%ul %unction : splits up a string and puts it on an $arra <e%ample = 8.y name is Nano Gough:7 Tname=split0/;sD/M<e%ample17 Tname = 8.y:M 8name:M 8is:M 8Nano:M 8Gough:

$using split ou can also assign elements to *ariables <name = 8Nano:Gough:7 0<firstUnameM <surname1=split0/;:/M<name17 <firstUname = 8Nano:7 <surname = 8Gough:7

Associati*e arra s " &as&es


*he elements of associati&e arrays ha&e ,eys with associated &alues Initiali!e F.ygrades=017 Assign elements <.ygradesQ>english?R=YP7 <.ygradesQ>irish?R=AP7 <.ygradesQ>maths?R=EP7 Printing while 00<,eyM<&alue1 = each F.ygrades1 Qprint 8<,ey =K <&alue;n:7R Prints: english =K YP irish =K AP maths =K EP

#ile &andling
Opening a %ile <filename =8.yZile.t%t:7 open0Z#LEMX/users/capg/ngough/perl/.yZile.t%tX1 OO die 0X'annot open file .yZile : <5;nX17 #ile: Zilehandle for .yZile.t%t +ie: #f the file cannot be opened for reading the program will die 0ie +uit e%ecution1 and the reason for this will be returned in ,*he abo&e file has been opened for reading : open0Z#LEM:[..17 *o open a file for writing: open0Z#LEM:K \utZile.t%t:17 \utfile.t%t will be o&erwritten each time the program is e%ecuted *o open a file for appending: open0Z#LEM:KK (ppend.t%t:17 'lose Zile: close0Z#LE17

#ile processing 4open input file for reading open0#NM:J #nZile.t%t:1 OO die 8'an?t open file[.<5;n:7 4open output file for writing open0\"*M:K \utZile.t%t:1 OO die 8'ant open file[.<5;n:7 while0J#NK1 Q <line=<U7 4read in the lines one at a time chop0<line17 4remo&e end of line character 4if <line meets conditional print to \utZile.t%t if0<line e+ 8Number A:1 Q R4end9hile close0#N17 close0\"*17 4close Ziles print \"* 8<line;n:7 R 4endif 4while there are still lines in #nZile.t%t

Regular expressions 4( regular e%pression is contained in slashesM and matching occurs with the ./ operator. 4*he following e%pression is true if the string the appears in &ariable <sentence. <sentence =~ /the/ 4*he RE is case sensiti&eM so if <sentence = X*he +uic, brown fo%X7 then the abo&e match will be false. <sentence 5~/the/ 0*rue1 because the 0lower case1 is not in <sentence 4*o eliminate case use i <sentence =~ /the/i7 0*rue1 because case has been eliminated with i

These Special characters can be used to match the following:


. ] < B D H ;sD ;dD ;t ;n ;b 4 (ny single character e%cept a newline 4 *he beginning of the line or string 4 *he end of the line or string 4 )ero or more of the last character 4 \ne or more of the last character 4 )ero or one of the last character 0matches one or more spaces1 0matches one or more digits1 0matches a tab1 0matches a new line1 0matches a word boundary1

4444444444444444444444444444444444444

An Example using RE0s


TAS1 : 9e ha&e a file containing lines in different formats. 9e want to pic, out the lines which start with a digit and end in a full stopM but remo&e the digit from the beginning of these lines while0JZ#LEK1 Q <line=<U7 chop0<line17 4 remo&es a newline at the end of the line if0<line =~ /];dD0.B;.1</1 Qprint 8<C;n:7R R ];dD 0specifies that <line must begin with one or more digits1
01 are used for grouping and remembering parts of the RE .B *his digit can be followed by any character any no. of times ;. *his is followed by a full stop 0*he slash is included to despecialise the >.? 1 <. *his specifies that the pre&ious character 0>.?1 must be the last on the line <C contains anything that has matched between the first pair of 01

RE0s contd Va!/W 0matches any lower case letter1 Va!/(!/W 0matches any letter1
#n the pre&ious e%ample a line was matched under the following condition: if0<line =~/];dD0.B1;.<1 T&e RE 2ould matc& t&e line: CP people went to the concert. ;dD = CP7 0.B1 = 8people went to the concert:7 Perl groups the elements specified by 0.B1 together and assigns it a default &ariable name : <C7 Print 8<C;n:7 4 prints : people went to the concert

Substitution
$substitution is a use%ul %acilit in perl 2&ic& can be used to replace one element 2it& anot&er 4replaces the first instance of london 0lc1 in <sentence to London 0uc17 <sentence =~ s/london/London/7 4replaces all instances 0because of g1 of red in <sentence to blue <sentence =~ s/red/blue/g7 E%ample <sentence= 8the red and white dress:7 <sentence =~ s/red/blue7 4 <sentence is now = 8the blue and white dress:

Some on3line Perl Tutorials: &ttp:""222.comp.leeds.ac.u4"Perl"start.&tml &ttp:""arc&i*e.ncsa.uiuc.edu"5eneral"Training"PerlIntro" &ttp:""222.pageresource.com"cgirec"index6.&tm Text boo4s: Perl coo,boo,7 *om 'hristiansen and Nathan *or,ington Programming Perl7 Larry 9allM *om 'hristiansenM and Randal L chwart/

You might also like