Vous êtes sur la page 1sur 70

Introduction to Perl Programming

Presentation for LX865 Gregory Garretson December 6, 2004 Originally a presentation for the Perl Learning Group !L"#$% clab&'b&'e(&)

Overview
*' **' *-' -' -*' + fe, intro(&ctory notes +bo&t Perl an( programming -ariables !on(itionals an( loops ./ercises

***' Perl basics

-**' 0ore st&ff

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 2

I. A few introductory notes

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 3

Caveats

*1m a ling&ist' * ha2e no formal bac3gro&n( in comp&ter science' *f yo& ha2e (iffic&lt 4&estions abo&t comp&ter science, as3 Pa&l' * (o 3no, ho, to program 4&ite ,ell in Perl, b&t * am not an e/pert' 5here are many, many things yo& can (o ,ith Perl, an( * ha2e learne( only a small s&bset of these'
6a2ing sai( that, feel free to as3 me things if yo& thin3 * can help ,ith yo&r e/ercises'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 4

Nomenclature

6ere are some terms that are &se( pretty m&ch interchangeably in this presentation' Don1t let this conf&se yo&'

script 7 program coding 7 programming execute 7 run evaluate 7 test

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 5

Formatting

8ormal e/pository te/t is in this font' 5e/t that represents ,hat you type is sho,n li3e so%

perl myprogram.pl

5e/t that represents comp&ter o&tp&t on the screen is sho,n li3e so%

File not found. C:\>

5hings ,ritten in angle brac3ets sho&l( be replace( ,ith the appropriate te/t%

perl <your program> -w


Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 6

II. A out Perl and programming

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 7

!"at is Perl#

Perl is an interpreted programming lang&age' 0ore on ,hat that means soon') +ny programming lang&age is essentially a h&man9frien(ly formalism for ,riting instr&ctions for a comp&ter to follo,' 5hese instr&ctions are at some point translate( into machine lang&age, ,hich is ,hat the comp&ter really :&n(erstan(s:'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 8

Programming languages vs. "uman languages

;ince ,e1re all ling&ists, it1s interesting to thin3 for a moment abo&t the (ifferences bet,een comp&ter lang&ages an( :nat&ral: lang&ages%

0ost programming lang&ages (o ha2e rec&rsi2e synta/, an( th&s can theoretically generate infintely comple/ str&ct&res, li3e h&man lang&age' +lso, programming lang&ages ha2e :synta/: an( :semantics:, an( something a3in to ,or( classes' 6o,e2er, programming lang&ages ha2e e/tremely small le/icons, an( 2ery restricte( syntactic r&les' +nother big (ifference is that comp&ter lang&ages (eal ,ith 2ery restricte( (omains compare( to h&man lang&ages, ,hich are m&ch more general an( fle/ible'
Slide 9

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Programming languages vs. "uman languages

*mportantly, comp&ter programs cannot tolerate ambig&ity<programs m&st be absol&tely precise' Pragmatics (oesn1t really enter into the pict&re= a comp&ter can1t :fig&re o&t ,hat yo& mean: in spite of ,hat yo& say i'e', no implicat&re)' *f there is a co&nter9e/ample to this, it is probably Perl, ,hich is e/tremely a(ept at :(oing the right thing:, ,ith a limite( amo&nt of e/plicitness in the instr&ctions' +lso, Perl li3e !O#OL an( some other lang&ages) ,as (esigne( to so&n( as m&ch as possible li3e .nglish, so it1s relati2ely &ser9frien(ly' >elati2ely'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 10

$"at said...

One big (ifference bet,een ,riting programs an( ,riting other sorts of (oc&ments is that yo&r programs m&st ha2e perfect synta/, or they ,ill not ,or3' .2ery little comma an( semicolon is critical' 5herefore, in ,riting co(e, it is 2ital to be absol&tely metic&lo&s' Other,ise, yo& ,ill ,eep an( gnash yo&r teeth an( generally not ha2e m&ch f&n' On the bright si(e, the synta/ is act&ally really easy' 0any, many times easier than in any h&man lang&age' On the e2en brighter si(e, Perl is a 2ery forgi2ing lang&age that allo,s for m&ltiple forms of e/pression' 5hat means that yo& can say something in 2ario&s ,ays, as long as yo&r synta/ is correct'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 11

%ou and your computer

* li3e to thin3 of it this ,ay% $"e computer is very energetic ut very very stupid.

5he comp&ter can (o things incre(ibly fast an( efficiently, b&t it can1t (o m&ch ,itho&t being tol( e/actly ho, to (o it'

*magine the comp&ter co&l( get yo& a glass of ,ater' *nstea( of saying :Get me a glass of ,ater: no nee( to be polite), yo& ,o&l( ha2e to say something li3e%
0o2e to the (oor, tra2elling north9east' ?hen yo& reach the (oor, locate the han(le an( rotate it co&nter9cloc3,ise a 4&arter t&rn' ;,ing the (oor to,ar(s yo&, mo2ing o&t of the ,ay as it approaches' 5hen procee( thro&gh the (oor,ay an( east to the 3itchen' Locate the refrigerator'''

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 12

!"y write programs#

5here are many reasons to ,rite yo&r o,n programs' ;ome are more ob2io&s than others'
@) ;ometimes yo& can1t fin( pre9e/isting soft,are to (o ,hat yo& nee( (one' 2) ;ometimes it1s easier an( faster to (o something yo&rself than to &se pre9e/isting soft,are' A) ;ometimes yo& ,ant a 2ery high (egree of control, one that yo& can1t get ,ith rea(y9ma(e soft,are' 4) Bo& (on1t ,ant to ha2e to hire someone else to ,or3 ,ith yo&r (ata, or other,ise ce(e control of yo&r ,or3' 5) Programming can get yo& 2ery close to yo&r (ata% yo& really see them an( thin3 abo&t them more than yo& might other,ise'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 13

!"y write programs#


6) Programming is an enCoyable mental challenge, li3e cross,or( p&DDles or chess, pro2i(e( yo&1re not in o2er yo&r hea(' *t1s a 2ery creati2e acti2ity' E) Programming is extremely satisfying ,hen it ,or3s' Bo& (isco2er a problem, imagine a sol&tion, ,rite a b&nch of co(e, an( the problem is sol2e(' *t offers a far greater sense of clos&re than most acti2ities in o&r fiel(' 8) Programming s3ills are re&sable lang&ages are pretty similar), an( programming can be &sef&l in all sorts of (omains, not C&st ling&istic research' F) Bo&r frien(s ,ill be very impresse('

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 14

Perl vs. ot"er programming languages

0ost programming lang&ages99s&ch as !, !GG, -is&al#asic, etc'99are compiled languages'

5o r&n a program, yo& create a te/t (oc&ment ,ith the co(e, r&n a compiler on it to con2ert it into machine co(e for yo&r O;, an( then r&n it'

Perl in an interpreted language, li3e Ha2a, Pascal, a,3, se(, 5cl, or ;malltal3'

5o r&n a program in s&ch a lang&age, yo& create a te/t (oc&ment an( tell the interpreter or -irt&al 0achine) to r&n it as a program' 5he interpreter chec3s it, compiles it into machine co(e, an( r&ns it' 5he 29step process of interprete( lang&ages ma3es them slightly easier to ,or3 ,ith' Bo& can constantly chec3 yo&r co(e by r&nning it after e2ery change'
Slide 15

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

&istory of Perl

Perl ,as (esigne( in the mi( @F80s by Larry ?all, then a programmer at $nisys, an( self9(escribe( :occasional ling&ist:' 6e combine( &sef&l feat&res of se2eral e/isting lang&ages ,ith a synta/ (esigne( to so&n( as m&ch as possible li3e .nglish' ;ince then, Perl has m&shroome( into a po,erf&l an( pop&lar lang&age, ,ith lots of mo(&les contrib&te( by the open9so&rce comm&nity' Perl is (esigne( to be fle/ible, int&iti2e, easy, an( fast= this ma3es it some,hat :messy:'

Perl has been calle( :a ;,iss9+rmy chainsa,: Perl is also 3no,n as :the (&ct9tape of the *nternet:
Slide 16

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Perl culture

*n many ,ays, Perl is a lang&age for :hac3ers:, not for comp&ter scientists' Perl is (is(aine( by people ,ho prefer lang&ages li3e !, ,hich are more rigi( an( closer to machine co(e' Larry ?all1s perspecti2e is this%

:Perl is a lang&age for getting yo&r Cob (one':

5,o other slogans that are 3ey to 5he Perl ?ay%

:.asy things sho&l( be easy, an( har( things sho&l( be possible': 505O?5D*% :5here1s 0ore 5han One ?ay 5o Do *t':

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 17

&ow you get Perl

One of the great things abo&t Perl is that it is entirely free' *t also r&ns on any platform o&t there' Bo& can get the so&rce co(e or a binary (istrib&tion from the ,eb' 5he main Perl repository is !P+8% the !omprehensi2e Perl +rchi2e 8et,or3

http%II,,,'cpan'org

5here is a binary (istrib&tion for ?in(o,s that yo& can get (irectly from the ma3ers, +cti2e;tate%

http%IIacti2estate'comI

+lso chec3 o&t these sites%

http%IIperl'comI

http%II,,,'perl'orgI
Slide 18

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

III. Perl

asics

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 19

'xecuting a script( way )*

5here are t,o ,ays of r&nning a Perl script% at the comman( line an( from a te/t file' Jor 2ery short scripts, yo& can C&st type t"e w"ole program at the comman( line an( ,atch the comp&ter r&n it'

C:\>perl -e "print 'Hello, World!'" Hello, World! C:\>

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 20

'xecuting a script( way )+

Jor longer scripts an( ones yo& ,o&l( li3e to re&se), yo& create a plain9te/t (oc&ment ,ith the program co(e an( then tell the Perl interpreter to r&n this program, &s&ally on the comman( line'

;a2e as :myprogram'pl:%

!!u"r!#in!perl print 'Hello, World!'$

5hen, on the comman( line%

C:\>perl myprogram.pl Hello, World! C:\>

Depen(ing on yo&r system, yo& might be able to r&n programs in 2ario&s ,aysK 5ry these o&t% perl myprogram.pl myprogram.pl myprogram
Slide 21

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

!riting a script

Perl scriptsIprograms are plain9te/t (oc&ments generally +;!**), &s&ally ,ith the e/tension 'pl, tho&gh this isn1t strictly necessary' Bo& can ,rite scripts in any ,or( processor, tho&gh * recommen( that yo& not &se 0; ?or( or another processor that by (efa&lt sa2es (oc&ments in some binary i'e', non plain9te/t) format'

;ee the ,i3i for lin3s to e(itor applications'

*t1s also 2ery helpf&l to &se a constant9,i(th monospace() font, s&ch as Courier %ew, beca&se then yo& ,ill be able to line &p yo&r co(e easily'
Slide 22

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

!riting a script

?e generally start a Perl script ,ith the :shebang: line, ,hich loo3s something li3e one of these%

!!u"r!#in!perl !!u"r!lo&al!#in!perl !!u"r!lo&al!#in!perl' !!u"r!#in!perl -w et&.

2ery &sef&lK

5his is not necessary on many systems, b&t ,hen it is, it is, so it1s a goo( habit to get into' 5he p&rpose of this line is to tell the ser2er ,hich 2ersion of Perl to &se, by pointing to the location in the ser2er (irectory of the Perl e/ec&table'
Slide 23

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

A first program

Let1s ,rite a first program' Open yo&r te/t9e(itor of choice an( type the follo,ing%

!!u"r!#in!perl print "Hello, World!\n"$

5hen sa2e the file as :helloL,orl('pl:' Preferably, sa2e all yo&r scripts in the same (irectory' * call my (irectory :scripts:' * (on1t &se :perl:, beca&se that ,here all the Perl files are') 8o, ,e nee( to tell the interpreter to e/ec&te the script' ?e (o this at the command line'

*n $8*X, this is calle( a shell= in ?in(o,s, a comman( prompt= in 0ac O; X, a 5erminal ,in(o,'
Slide 24

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Getting to t"e command line

*n ?in(o,s% !lic3 on Command Prompt' 5o get there, yo& may ha2e to loo3 &n(er ,tart-.All Programs-.Accessories *n 0+! O; X% !lic3 on $erminal' 5o get there, yo& may ha2e to loo3 &n(er Applications-./tilities *n $8*X% *f yo&1re r&nning $8*X, yo& are in a shell, pro2i(e( yo&1re logge( on' 5he same goes for X9?in(o, or a similar program'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 25

Navigating in t"e s"ell

8ote% 5he prompt may loo3 (ifferent ,ays, (epen(ing on yo&r system' $s&ally, it tells yo& ,hat (irectory yo&1re in' 8ote that it1s often c&stomiDable' 6ere are some e/amples%

C:\"&ript"> !(regory!"&ript") *+ome-Computer:,!"&ript"-gregory.

Bo& really only nee( to 3no, one comman( to get aro&n( in the shell% c(' #&t it also helps to 3no, ls (ir in ?in(o,s) an( p,('

0o2e to (ir 1scripts1

mo2e &p one (ir

&d "&ript"

&d ..
Slide 26

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

0asic Perl syntax

Perl thin3s of :lines: (ifferently from h&mans' Jor &s, the most important thing is the carriage ret&rn= for Perl it is the semicolon' +ll lines of co(e in Perl m&st en( ,ith one of t,o things% a semicolon or curly races%

print "Hello."$ "u# /print "Hello."0

+ line of co(e, calle( a statement, is basically a single instr&ction to the comp&ter= it says, :Do x': *t can e/ten( o2er more than one line of the page' +nything in M N is calle( a loc1' + bloc3 can contain se2eral statements'
Slide 27

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Comments

+ny line that begins ,ith the character ) is treate( by Perl as a comment an( is ignore(' 5his means that yo& can p&t lots of comments for h&mans to rea( in yo&r co(e, ,itho&t affecting the program' 5his is a very good idea' 5he O can act&ally come at any point in the line% ,hate2er comes after it ,ill be ignore(' #&t in that case ,hat comes before it ha( better be a 2ali( line of co(eK

12i" ne3t line "ort" alp2a#eti&ally 4name" 5 "ort 64name"7$ 67 optional


Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 28

2uote mar1s

Perl ma3es &se of three basic 3in(s of 4&ote mar3s% single 1 1), (o&ble : :), bac34&otes P P) Bo& ,ill &s&ally ,ant to &se (o&ble 4&otes' +s a general r&le, &se the others only if yo& ha2e to' Do&ble 4&otes allo, varia le interpolation' 5hat means that this co(e%

)name 5 "8le9na"$ print "Hello, )name!\n"$

5hese are the 4&otes to ,atchK

,ill print this%

Hello, 8le9na!

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 29

2uote mar1s

;ingle 4&otes ,ill pre2ent interpolation' 5hat means that this co(e%

)name 5 "8le9na"$ print 'Hello, )name!\n'$

,ill print this%

Hello, )name!\n

#ac34&otes P P) r&n an e/ternal program an( grab the o&tp&t' Bo& ,ill rarely, if e2er, &se these'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 30

0ac1slas" interpolation

Perl has a n&mber of special characters that ha2e a partic&lar meaning ,ithin (o&ble 4&otes an in reg&lar e/pressions' 6ere are t,o important ones%

\n \t

mean" "newline" a.:.a. "&arriage return" mean" "ta#"

;o, here1s ,hat ,e can type an( ,hat ,e1ll get%

print "%ame:\t;e&:y\n<ye":\t2a=el\n"$ %ame: ;e&:y <ye": 2a=el

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 31

I3. 3aria les

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 32

4ata types in Perl

0ost (ata is basically either a string or a num er, or a b&nch of strings or n&mbers' + string is character (ata% :froggy:, :@@9A0904:'

+l,ays ,rite strings ,ithin 4&ote mar3s, as abo2e'

+ num er is e/actly ,hat yo& thin3 it is' 8ote, ho,e2er, that a gi2en piece of (ata that loo3s li3e, say, A00, can be treate( li3e a n&mber e'g', A00 G @) or li3e a string e'g', thro&gh concatenation% A00a)' $nli3e other programming lang&ages, Perl ta3es a 2ery rela/e( attit&(e to,ar( this (istinction' *t basically loo3s at ,hat yo&1re trying to (o an( treats the (ata as the appropriate type'
Slide 33

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

3aria les

5he concept of the varia le is f&n(amental in all programming lang&ages' + 2ariable is essentially a placehol(er for a 2al&e' ?e 3no, 2ariables from basic algebra%

*n x 5 * 6 7, x is a 2ariable'

$se of 2ariables in programming (iffers a bit from algebra% ?e spen( a lot of time creating 2ariables, assigning 2al&es to them, changing the 2al&es, an( rea(ing the 2al&es' -irt&ally all (ata is store( in 2ariables' ?e manage this information thro&gh operators li3e G) an( f&nctions li3e print)'
Slide 34

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

,calars

*n Perl, the three most important types of 2ariables are the scalar, the array an( the "as"' + scalar is a 2ariable that hol(s a single 2al&e' ;calar names begin ,ith 8%
3A9IA0L' 3AL/'

)name 5 "8i"2a"$ )age 5 ">?"$

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 35

Arrays and "as"es

5here are t,o 3in(s of 2ariables that hol( m&ltiple pieces of (ata% arrays an( "as"es' +n array is a 2ariable that hol(s m&ltiple 2al&es in series' +rray names begin ,ith :%

4name" 5 6"Howard", "@e"lie", ";o#"7$

+ "as" is a 2ariable that hol(s pairs of (ata' 6ash names begin ,ith ;%

.trait" 5 6"name" 5> "Howard", "age" 5> "A?", "eye"" 5> "#rown"7$

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 36

3aria le names

5he name of a 2ariable ,hether scalar, array, or hash) begins ,ith the special type9in(icating character 8, :, or ;, respecti2ely), an( then can contain any combination of letters, n&mbers, an( &n(erscores'

6o,e2er, the first character after the 8, etc' m&st be a letter or &n(erscore, not a n&mber' +lso, case *; (istincti2e' ./amples of 2ali( names%

)timeBofBarriCal, )1imeBofB8rriCal )timeofdeparture, )1DE )1imeFG>(o if yo&1re chil(ish)


Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 37

Good naming practice

?hen yo& choose 2ariable names, choose ill&strati2e ones, not obsc&re ones%
#+D GOOD

)3 5 "Ho2n"$ )y 5 ";ate""$

)fir"tBname 5 "Ho2n"$ )la"tBname 5 ";ate""$

* ma3e a point of &sing sing&lar names for scalars an( pl&ral names for arrays an( hashes%

)per"on 5 "C2ri"tine"$ 4people 5 6"C2ri"tine", "Hean"7$

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 38

$wo 1inds of operators

5he important one to ,atch o&t for is the :smooth operator:' 8o, C&st 3i((ing' + &sef&l (istinction to 3eep in min( is that bet,een assignment operators an( comparison operators' 5he former give a 2al&e to a 2ariable, an( the latter test the 2al&e of a 2ariable'

5o set the 2al&e of a 2ariable%

)limit 5 I??$

5o test the 2al&e of a 2arable%

*f this ,ere a speech act, it ,o&l( be a performative'

if 6)num#er 55 I??7 /print "@imit!"0


*f this ,ere a speech act, it ,o&l( be a <uestion' Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 39

!or1ing wit" scalars

?e assign a 2al&e to a scalar &sing the assignment operator 6, ,hether ,e are (ealing ,ith strings or n&mbers'

)name 5 "<liani"$ )grade 5 I??$

?e can perform math on a scalar if it ma3es sense to (o so%

)grade 5 6)grade J A?7!I??$

?e can perform concatenation on strings ,ith the . operator%

)name 5 )fir"tBname . " " . )la"tBname$ now )name i", e.g., "Kary Hug2e""
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 40

!or1ing wit" arrays

?e can assign 2al&es to arrays in 2ario&s ,ays' 5he most straightfor,ar( is to &se parentheses, ,hich create a :list conte/t:%

4grade" 5 6"LM", "MF", "NA", "ML"7$

5he 2al&es in an array are n&mbere( or indexed), starting wit" =, rather than @' ?e can access any 2al&e in an array by referring to its n&merical in(e/ in s4&are brac3ets%

print ")grade"*?- and )grade"*>-"$ LM and NA

8ote that ,e &se 8 rather than :, beca&se here ,e1re referring not to the ,hole array, b&t to one element in it, ,hich is a scalar'
Slide 41

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

!or1ing wit" arrays

?hen ,e print an array, it ma3es a (ifference ,hether ,e p&t it in (o&ble 4&otes or not= if ,e (o, ,e get spaces bet,een the elements'

4OD1" 5 6"F??", "ANM", "A'>"7$ print 4OD1"$ F??ANMA'> print "4OD1""$ F?? ANM A'> print '4OD1"'$ to reCiew 4OD1"

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 42

Input

Perl nee(s (ata to interact ,ith' 5his (ata typically comes from one of three so&rces% 3eyboar( inp&t, files, or the system the ser2er)'

?e1re only going to co2er the first of these to(ay'

*np&t from the 3eyboar( is so stan(ar( that ,e call it :stan(ar( inp&t:, abbre2iate( ,$4IN' 6ere1s ho, ,e get some inp&t from the 3eyboar(%

)input 5 <+1EP%>$

5his assigns to 8input ,hate2er the &ser type(' $nfort&nately, this also incl&(es the ne,line from ,hen they hit :.nter:, so ,e ta3e that off li3e so%

&2omp 6)input7$

t2e 67 are optional


Slide 43

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

3. Conditionals and loops

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 44

Conditional statements( if

Of co&rse, the po,er of programs comes from their inp&t to react (ifferently to (ifferent (ata' 5he conditional statement is the 3ey to this' 5he if statement has t,o parts% a condition, ,hich is e2al&ate(, an( a loc1, ,hich is e/ec&te( if the con(ition e2al&ates to be tr&e'

if 6)pri&e > I??7 / print "1oo e3pen"iCe!\n"$ 0

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 45

Conditional statements( elsif

+n if statement can optionally be follo,e( by an elsif statement' 5his is e2al&ate( after the if statement only if t"e previous condition evaluated >t"e if statement?s@ was false' 5he t,o bloc3s ,ill ne2er both be e/ect&te('

if 6)pri&e > I??7 /print "e3pen"iCe"0 el"if 6)pri&e < I?7 /print "#argain!"0 el"if 6)pri&e < F?7 /print "&2eap"0

+gain% *f the if statement e2al&ates to tr&e, the elsif statements are C&st s3ippe(' ;imilarly, if the first elsif e2al&ates to tr&e, the secon( is s3ippe('

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 46

Conditional statements( else

+n else statement is a special 3in( of elsif that co2ers all remaining con(itions' *n ling&istics, this is 3no,n as :the else,here con(ition:'

if 6)grade < Q?7 / print "Failing grade!: )grade\n"$ 0 el"e /print "(rade i" )grade.\n"0

8ote that there is no con(ition to be e2al&ate( in an else statement, beca&se it1s the :garbabe can: category an( is al,ays tr&e'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 47

Loops

+ maCor reason ,e &se comp&ters is that they can (o the same thing many times ,itho&t getting tire( or nee(ing coffee' ?e get them to repeat actions &sing iterative or looping constucts' 5here are three main types of loop statement, ,hich are all relate( b&t specialiDe( for (ifferent &ses% for, foreac", an( w"ile statements'

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 48

?w"ile? loops

!"ile statements are the least comple/ of the three types, so ,e1ll start there' 5hey are similar to con(itional statements, beca&se they ha2e a con(ition an( a bloc3' *f the con(ition e2al&ates to tr&e, the bloc3 is e/ec&te(' 5hen, the con(ition is e2al&ate( again, an( if it?s still true, the bloc3 is 5his represents e/ec&te( again, an( so on'

w2ile 6)money < I???7 / )pay 5 (etBRay&2e&: 67$ )money 5 )money S )pay$ 0 print "D:, we &an pay t2e rent!\n"$
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

some &ser9(efine( s&bro&tine, ,hich pres&mably chec3s for more money an( ret&rns the 2al&e as 8pay'

Slide 49

?until? loops

/ntil statements are a special type of w"ile statement in ,hich the bloc3 is e/ec&te( until t"e condition evaluates as true' *t1s e4&i2alent to :,hile 8O5 con(ition)''':'

until 6)money < I???7 / )money 5 <atBDut 6)money7$ 0 print "1ime to eat noodle"!\n"$

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 50

?for? loops

For statements are 2ery &sef&l, beca&se they allo, yo& to (o something a preset n&mber of times, or &ntil a con(ition becomes tr&e' 5heir str&ct&re is more comple/ than a ,hile statement1s%

for 6)i 5 I$ )i <5 I??$ )i SS7 / print "We'Ce rea&2ed )i\n"$ 0 We'Ce rea&2ed I We'Ce rea&2ed > ... We'Ce rea&2ed I??
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 51

?for? loops
5his sets the initial 2al&e of the 2ariable% its 2al&e on the first pass thro&gh the loop' 5his sets the test that (etermines ,hen to e/it the loop% as long as this is tr&e, the loop ,ill be rer&n' 5his sets ho, the 2ariable ,ill be incremente( on each pass thro&gh the loop'

for 6)i 5 I$ )i <5 I??$ )i SS7 / print "We'Ce rea&2ed )i\n"$ 0 We'Ce rea&2ed I We'Ce rea&2ed > ... We'Ce rea&2ed I??
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 52

?foreac"? loops

Foreac" statements allo, &s to perform the same operations on e2ery element of an array or hash in series' 5hey temporarily assign the 2al&e of each element to a scalar that ,e can ,or3 ,ith'

forea&2 )grade 64grade"7 / if 6)grade < Q?7 / print "Failing grade!: )grade\n"$ )failBtally SS$ 0 0 print "We 2aCe )failBtally failing "tudent"!\n"$
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 53

'xiting t"e loop

;ometimes yo& ,ant to e/it the loop 2ia a metho( other than the stan(ar( one' ?e (o this &sing the statements next, redo, an( last' next means :s3ip o2er e2erything else in the bloc3, increment the co&nter, an( e2al&ate the con(itional again': redo means :s3ip o2er e2erything else in the bloc3 an( e2al&ate the con(itional again, ,itho&t incrementing the co&nter': last means :e/it the bloc3 an( ne2er come bac3':

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 54

'xiting t"e loop

6ere1s an e/ample that &ses both next an( last%

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

forea&2 )"tudent 64"tudent"7 / if 6)"tudent eT "<%EBU<(P+1<U<E"7 / la"t$ 0 el"if 6)"tudent eT "+il#er"7/ ne3t$ 0 el"e / )grade 5 C2e&:B(rade 6)"tudent7$ 0 print ")"tudent: )grade\n"$ 0
Slide 55

3I. 'xercises

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 56

'xercise *

6ere is a command line script that print :6ello, ,orl(K: ?in(o,s 2ersion<others may ,ant to &se single 4&otes)%

perl -e "print TT!Hello, World!\n!$"

8ote that insi(e the : :, ,e &se 44I I instea(= this is beca&se ,e can1t nest (o&ble94&otes' 5hese are e4&i2alent%

"2ello" 5 TT!2ello!

?rite a script on the comman( line that greets yo& instea( of the ,orl(' 5hen a(( some co(e so that it prints t,o messages on t,o lines'
Slide 57

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

'xercise +

6ere is a program to be ,ritten in a te/t file) that prints again on the screen ,hate2er yo& type' 0o(ify it so that it as3s for yo&r name an( greets yo& by name'

8ame% !all it 1greet'pl1'

!!u"r!#in!perl -w print "1ype "omet2ing: "$ )"omet2ing 5 <+1EP%>$ &2omp )"omet2ing$ print ")"omet2ing\n"$
5his is a terrible 2ariable name' !hange it to something more appropriateK
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 58

'xercise A

?rite a program that, gi2en the base form of a 2erb thro&gh ;5D*8), o&tp&ts the correct Ar(9 person sing&lar form'

8ame% !all it 1conC&gate'pl1' 8O5.% Don1t forget abo&t irreg&lar formsK 8O5.% Bo& can lea2e o&t all negati2e forms' 8O5.% Bo& can also ignore forms li3e :,atches:' ?e1ll (o those ones once ,e get to reg&lar e/pressions)

6*85% Bo& ,ill probably ,ant to &se the follo,ing things%

if

el"if

el"e

eT

.
Slide 59

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

3II. Bore stuff

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 60

Opening files

Perl ma3es it fairly easy to loa( (ata from files' 5o (o this ,e &se the open an( close f&nctions, an( the :angle9operator: C .' 6ere1s a simple e/ample%

)inputBfile 5 "#igoldfile.dat"$ open 6P%RG1, ")inputBfile"7$ w2ile 6)line 5 <P%RG1>7 / print ")line"$ 8ote that this prints to 0 ;5DO$5, or the screen' &lo"e 6P%RG17$

*8P$5 is ,hat1s 3no,n as a file"andle' *t1s a temporary name for a file' ;5D*8 is a filehan(le too'
Slide 61

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Creating files

?e can &se the same comman(s to o&tp&t to a file that the program creates'

)inputBfile 5 "#igoldfile.dat"$ )outputBfile 5 "output.t3t"$ open 6P%RG1, ")inputBfile"7$ open 6DG1RG1, ">)outputBfile"7$ w2ile 6)line 5 <P%RG1>7 / print DG1RG1 ")line"$ 0 5his . ma3es all the (ifference' *t means that this file is being &lo"e 6P%RG17$ ,ritten to, not rea( from' &lo"e 6DG1RG17$
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 62

$"e ?split? function

5he f&nction split enables &s to easily transform a scalar to an array, by splitting the scalar &p on spaces or another character'

)"enten&e 5 "+ue and P "plit up."$ 4word" 5 "plit6! !, )"enten&e7$ print ")word"*F-\n"$ 5hat1s a space' up.

?e can also split on commas, etc'

)li"t 5 "<enie, meenie, miney, moe"$ 4word" 5 "plit6!,!, )li"t7$ print ")word"*A-\n"$ moe
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 63

Counting elements in an array

?e often ,ant to 3no, ho, many elements are in an array' 5here are three ,ays to get this info'

5he f&nction scalar%

4people 5 6"Koe", "@arry", "Curly"7$ print "&alar64people7 . "\n"$ A

$se of :scalar conte/t:%

)&ount 5 4people$ print ")&ount\n"$ A

$se of 8), ,hich gi2es the last index of an array%

print ") people"$ > Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 64

Finding t"e lengt" of a string

5he f&nction lengt" can be &se( to fin( to length in characters of a scalar'

)"tring 5 "a#&defg2i9"$ )2ow#ig 5 lengt26)"tring7$ print ")2ow#ig\n"$ I?

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 65

$"e ?sort? function

Bo& can sort the elements of an array or the 3eys of a hash ,ith the f&nction sort' #$5% #y (efa&lt, it sorts both strings an( n&mbers alphabeticallyK

4array 5 6";etty", "Cat2y", "8##y"7$ 4array 5 "ort64array7$ print "4array\n"$ 8##y ;etty Cat2y

#&t ,atch o&t%

4array 5 6"A", "F?", ">F", "I??"7$ 4array 5 "ort64array7$ print "4array\n"$ I?? >F A F?
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 66

,orting array 1eys

+ 2ery common type of loop ma3es &se of the f&nctions sort an( 1eys' 5he latter yiel(s all the 3eys not the 2al&es) in an array'

."ign" 5 6"Fran:" 5> "Capri&orn", "8manda" 5> "+&orpio"7$ forea&2 )per"on 6"ort :ey" ."ign"7 / print ")per"on: )"ign"/)per"on0\n"$ 0 8manda: +&orpio Fran:: Capri&orn

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 67

Adding elements to arrays

5here are t,o ,ays of a((ing ne, elements to e/isting arrays' *f ,e 3no, the in(e/ ,e ,ant the element to ha2e, ,e can (o this%

4num#er" 5 6">I?", "F'?", "AAA"7$ )num#er"*A- 5 "LL?"$

*f ,e simply ,ant to a(( an element to the en( of an array, ,e can &se pus"%

pu"264num#er", "LL?"7$

*n either case, "n&mbers is no,%

>I? F'? AAA LL?


Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 68

$a1ing elements out of arrays

5he re2erse of pus" is pop, ,hich ta3es remo2es the last element from the array%

4num#er" 5 6">I?", "F'?", "AAA"7$ )la"t 5 pop64num#er"7$ print ")la"t\n"$ AAA

8ote that this is (ifferent from saying

)la"t 5 )num#er"*>-$
beca&se this (oesn1t remo2e the element from the array' +fter pop, the array ,ill ha2e only 2 elementsK
Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04) Slide 69

$"at?s allD

Introduction to Perl Programming (presentation by Gregory Garretson, 12-06-04)

Slide 70

Vous aimerez peut-être aussi