<<

Introductionto BasedLooselyonLearningPerl,2ndEd byRandalSchwartz&TomChristiansen

Cogs,FlywheelsandRubberbands (version1.2) ITComputingServices February1998 February2002 PartI expression,decisionsandflowcharting if while 3 Housecleaningitem: print(…);vs.printf…;

• Upuntilnow,Ihavebeenusingprintinthefollowingway: print(”blah”); butyoucanalsoomittheparentheses: print”blah”; whichisniceandsimple.

Iwouldprefertoincludetheparenthesesbecauseitismore-likeand lessambiguous(inmymind)aboutwhattheparametersare.

• Iwouldalsoliketobeginusingtheprintf()functioninsteadofthe print()function.Asyouwillseelater,printf()ismore flexiblethanprint(). 4 HouseCleaning:OtherOperatorsI “Neglected”toMention

• Ihadtalkedaboutoperatorslasttimesuchas“+”,“-”,“.” and“=”.ThereisaclassofoperatorsthatIhaveleftout: therelationaloperators:

NumericalRelationalOperators == equal != notequal < lessthan > morethan <= lessthanorequalto >= greaterthanorequalto 5 …Operators(cont’)

StringRelationalOperators eq equal ne notequal lt lessthan gt morethan le lessthanorequalto ge greaterthanorequalto

andtherewillbemore.

• Arelationaloperatormakesacomparisonbetweentwo valuesandreturnsaTRUEorFALSE. 6 ExamplesofUsing RelationalOperators

• Suppose$a=3,$=4,$i=1and $first=“Bill”,$last=“Clinton”,$full=“BillClinton”

expression result expression result $a==3 TRUE $b>=$a TRUE $a>$b FALSE $b-$a==$i TRUE

expression result $firsteq“Bill” TRUE $first.““.“$lasteq“BillClinton” TRUE $last<$first FALSE 7 Whatistruth?

• Inotherwords,whatisconsideredTRUE?

TRUEisdefinedinPerl(aswellasmanyotherlanguages) asanon-zerovalue:

expression result 1==1 TRUE 1==0 FALSE

1 TRUE 3 TRUE 0 FALSE 8 ASlightbutImportant Diversion:Flowcharts

• Giveusavisualrepresentationormappingofhowa programflows. • Flowchartingisjustaninterestingwayofthinkinghowto program. • It’sausefultoolespeciallyforlearning,butasyouwill soonsee,itcan’tbescaledupintofull-blownprograms. Youcantry... 9 AProcessStatement m a g o r p e h t

dosomething f o w o l f

• Withprocessstatements,wedosomething. Agoodexampleofoneistheprintf statement:printf(“Hellothere.\n”); 10 Grouping: BracesaroundBodiesofBoxes • Therewillbetimeswhen wewanttogroupmany m a

processstatements.We r

pullout g o usuallydothisbecausewe cigarette r p

aregroupingsmaller e h t light processestoformalarger f o cigarette

process.Andtodothis,we w o l usuallyusecurly-braces: puff f {and}. cigarette 11 TheDecisionBox 1 2 • Upuntilnoweverystatement y y t t i thatwe’veseenandusedhas i l l i i b b i beenonepath.So,the i s s s s o programswe’vewrittenhave o p p beenlikealongriver:very w w o o l linear.Prettyboring. l f f Test • AndtheDecisionBoxchanges False theflowofaprogram.Thisis alotlikeaforkedriver. True 12 Example:ASimpleDecison withOutcome • DecisionsShouldHave Outcomes!Adecision withoutanoutcomeisnota $nameeq F usefuldecision! “Barry”

T • Noticetheelementsofthe this:DecisionandOutcome whenTRUE. printf(“Hello Barry.\n”); • Whathappensifthedecision isnotTRUE? 13 ADecisionw/OutcomeinPerl

• Noticetheextrasyntaxremindersaddedhere! Noticethecurly-bracesforthebodiesof processstatements.Noticealsothe $nameeq F parenthesesthatsurroundthetest.Always “Barry” surroundthetestwithparentheses! ( ) T • AdecisionwithanoutcomeinPerltakesthe form: if(expr){body} printf(“Hello Barry.\n”); • Andasinourexample: if($nameeq“Barry”){ printf(“HelloBarry.\n”); } AMoreComplicatedDecision: 14 TwoOutcomes

Whatdoesthisdo?

$nameeq F “Barry”

T printf(“You’re notBarry.\n”); printf(“Hello Barry.\n”); ...AndnowinPerl 15 if(expr){body1}else{body2}

$nameeq F ( “Barry” ) T printf(“You’re notBarry.\n”); printf(“Hello Barry.\n”);

• andwewritethisinPerlas:

if($nameeq“Barry”){ printf(“HelloBarry.\n”); }else{ printf(“You’renotBarry.\n”); } 16 Bewareofthe TwoTypesof • This $a==3 Thistestsforequality. isdifferentfrom $a=3 Thisassignsthevalueof3to$a.

• So,don’teverwrite:

if($a=3){ printf(“aisnow3!\n”); }

(Makethis$a==3instead!) (Imadethisdumbmistakewhenwritingthispresentation.) 17 BewareofAnother KindofEquality • This $name==“Barry” Thistestsforequalityfor numbersandiswrong!. isdifferentfrom $nameeq“Barry” Thisassignstheequalityin stringsandiscorrect.

• So,don’teverwrite:

if($name==“Barry”){ printf(“HelloBarry!\n”); }

(Imadethismistaketoowhenwritingthispresentation.) 18 Excerciseswithif’s

• 1)Writethecodefragmentforthisrather contrivedandmeaninglessexample:

T $catch printf( !=22 “Rock.\n”)

F printf( “Hard place.\n”); Andhowdoesitwork? Whathappensif$catchis11?22?0? 19 Excerciseswithif’s(cont’d)

• 2)Whatifyoudidnothaveelseinyourlanguagelikesomeolder computerlanguages?Rewritethiscodefragment:

if($nameeq“Barry”){ printf(“HiBarry.\n”); }else{ printf(“You’renotBarry.\n”); }

• 3)Supposeyouhadthisvariablecalled$indian,andyouhadto printftheword“One”ifthevalueof$indianis1and“Two”ifthe valueof$indianis2andsoonupto5.Writethecodefragment forthat. 20 ANew&MoreInterestingKindofDecisionStructure

$num_indian =0 T printf( $num_indian $num_indian “$num_indian !=10 ++ ( ){ littleindian.\n}”)

•Whatwillthisdo? F printf( “Tenlittle indianboys.\n”) •Hereisanotherwaywhichwecan divergefromthelinearwayof programming.Theifstatementallowedustojustbranchoffto anotherpossibleflow.Thisnewwayallowsustoreturntothe decisionagainsometimelater.Thisisknownasaloop. 21 Thewhile(expr){body}Loop

$num_indian =0 T printf( $num_indian $num_indian “$num_indian !=10 ++ ( ){ littleindian.\}n”)

F printf( “Tenlittle • Andthistypeofloopisknown indianboys.\n”) asthewhileloop.HereitisinPerl:

• $num_indian=0; while($num_indian!=10){ $num_indian++; printf(“$num_indianlittleindian.\n); } printf(“Tenlittleindianboys.”); FourAreasofInterestofthe 22 while(expr){body}Loop

Area1 Initialization BodyofLoop T Area4 Area2 Area3 Incrementor Test ) Dosomething UpdateState ( { ofLoop }

F Outsideof Loop

• Area1:Beforetheloopstars,startoffwithsome-uporinitial conditions. Area2:Makeatest,gointoloop(again)orcontinueon? Area3:Dosomething(whateveryouwrotetheloopfor) Area4:Incrementorchangethestateoftheloop. OutsidetheLoop:Loopfinishes.Notveryinteresting.Sometimes neededtorepackagetheanswerforanotherpartofthecode. FourAreasofInterestofthe 23 while(expr){body}Loop(cont’d)

Area1 Initialization BodyofLoop T Area4 Area2 Area3 Incrementor Test ) Dosomething UpdateState ( { ofLoop }

F Outsideof Loop

• SometimesArea4mightseemlikeitcanbeincludedinArea3,butit servesanimportantenoughpartthatitcanstandonitsown.Area4is likethehousekeepingpartoftheloop.

YoucouldsaythatArea3doesallthe“important”workoftheloop andArea4hastheresponsibilityofkeepingtheloopgoing. 24 There’smorethanonewayto writealoop...

• TheexampleoftheTen-little-indianprogramdoesn’t fitourexample.Noticethattheincrementisatthe beginningoftheloop;andmymodelofloopsputsit attheend.

Let’srewritetheloopsothatitdoesfollowthatform. There’sagoodreasonforthis.I’llsaymore 25 AMatterofStyle

#!/opt/local/bin/perl I(personally)liketowritemy $num_indian=0; perlscriptsthisway.This followsastyleinCcalled while($num_indian!=10) { K&Rstyle.Noticethe $num_indian++; printf(“$num_indianlittleindian.\n); beginningbracebeginsonthe endofthelineofthetestand } theclosingbracelinesupwith printf(“Tenlittleindianboys.”); thelineofthetest.It’sgreatat conservingscreenspace.

#!/opt/local/bin/perl $num_indian=0; while($num_indian!=10) Thisisalsoaperfectlyvalidwayto indentyourprograms.Andthisis { morelogicalforbeginners.A $num_indian++; beginningbracebeginsonthenext printf(“$num_indianlittleindian.\n); lineofaloopandtheclosingbrace linesupwiththebeginningbrace. } Butyou’llseemeuseK&Rstyle. printf(“Tenlittleindianboys.”); Sorry. 26 AMatterofStyleII

Styleisnotonlycurly-braces.Indentationishelpsyoukeeptrackof multipleloops.Wewon’tgetintothisnow,butIwanttosufficiently scareyouintogoodhabits.Noticethetwoloops(oneinsidetheother) andhoweasyitistoseethem: MainProgram $minute=10; while($minute!=0){ OuterLoop printf(“Beginningminute$minute.\n”); second=60; while($second!=0){ InnerLoop printf(“\tsecond$second.\n”); $second--; } print(“Endingminute$minute.\n”); $minute--; }

Indentyourprogramstoo!!!Oryou’llbesorry... 27 while(expr){body}Benchpresses

1)Writethecodefragmentforthisflowchart:

printf(“Theshuttle ispreparing fortakeoff.\n”); $time=30; T printf(“Tminus $time!=0 $timeand $time--; ( ){ counting.\n); } F Whatnewconceptisin printf(“Blast thisfragment/flowchart? off!\n); 28 while(expr){body}Benchpresses: MoreReps

• 2)Havetheuserenterintennumbersandhavethe computercomputethesumandaverageofthoseten numbers.

• 3)Dothesameexcepttheusergetstochoosehowmany numbersthecomputermustsumandaverage.I’mleaving thisonevague. 29 AllYouNeediswhileandif

• Youcandojustabouteverythingyouwantwith onlywhile(expr){body}and if(expr){body}constructs!

• Allotherloopconstructswewillbetalkingabout arevariantsoforaremadeofdifferent combinationsofwhileandif.Sometimesit takesmoreworkandyouhavetobecreativeabout howyoucodesomesituations…,butitcanbe done!Wewilltalkaboutthevariantssoon. 30 SuggestedReadings

• Chapter4:ControlStructures(2ndEd)

sections: StatementBlocks(pg.58) Theif/unlessStatement(pgs.59-60) Skipthepartaboutunless;we’llcomebacklater. Thewhile/untilStatement(pg.61) Skipthepartaboutuntil;we’llcomebacklater.

Skipthesectiononforandforeach,that’snexttime&later. 31 SuggestedReadings

• Chapter2:ScalarData(3rdEd)

sections: ComparisonOperators(pg.33) ifControlStructure(pg.34) whileControlStructure(pg.37) BooleanValues(pg.34) GettingUserInput(pg.35) 32 SuggestedHomework Sendsolutions(codeandoutput)to[email protected] • PROBLEM0:Typeineveryprograminthispresentation andtrythemout. 1littleindian • PROBLEMS1,2,3:DoinLearningPerl,Chapter4: 2littleindian 3littleindian pg.65(2nded.) 4littleindian 5littleindian 6littleindian • PROBLEM4:Therewasasmallproblemwiththe 7littleindian 8littleindian Ten-Little-Indianprogram.Itwouldcountindiansin 9littleindian 10littleindian numbers(1,2,3...)andattheend,itwouldsay“Ten Tenlittleindianboys

littleindianboys.”That’sinconsistent. 1littleindian 2littleindian 3littleindian a)Easy(?):Changetheprogramsothatatthelastline 4littleindian 5littleindian “Tenlittleindianboys.”isnowconsistentwiththe 6littleindian 7littleindian countingpartoftheprogram.ThinkaboutwhatI’m 8littleindian 9littleindian askingyoutodo.Keepasparecopyoftheoriginalprogrambeforeyou 10littleindian do(a)becauseproblem(b)hasnothingtodowith(a). Fixlastline! 10littleindianboys 33 SuggestedHomework(cont’d)

Onelittleindian Fixthese! Twolittleindian Threelittleindian b)Morechallenging:Changetheprogramsothatthe Fourlittleindian Fivelittleindian countingisnowconsistentwiththelastline“Tenlittle Sixlittleindian Sevenlittleindian indianboys”.You’llneedalotofifstatementsinside Eightlittleindian Ninelittleindian thewhileloop. Tenlittleindianboys Makeanextrasparecopyofyourfinished(b);parts(c)and(d)dependon(b). Tenlittleindianboys

Onelittleindian c)Noticethat“Tenlittleindianboys”isrepeatedtwice. Twolittleindian Threelittleindian That’snothowthesonggoes.Modifythetestinthe Fourlittleindian Fivelittleindian loopsothatyouonlygetthelastlineoncenow.Modify Sixlittleindian Sevenlittleindian thetest. Eightlittleindian Ninelittleindian Tenlittleindianboys 34 SuggestedHomework(cont’d) Onelittleindian Twolittleindian d)Thereisanotherwaytoprint“Tenlittleindian Threelittleindian Fourlittleindian boys”onceandithasnothingtodowiththeloop Fivelittleindian Sixlittleindian orthetest.Howdoyoumodifytheprogram? Sevenlittleindian Eightlittleindian Modifyit. Ninelittleindian Tenlittleindianboys • PROBLEM5: a)Writeaprogramthatprintsout1to10(eg:1,2,3…) andprintsoutthevalueasitiscounting.Useawhile loop. b)Nowhaveitprintoutfrom2to20by2’s(eg:2,4,8,…) withoutchangingthetestcondition.Youmayonlychange onelineofcode.Hint:trytodo(c)first. c)Nowhaveitprintoutfrom0.5to5.0by1/2’s(eg: 0.5,1.0,1.5,…)withoutchangingthetestcondition.You mayonlychangeonelineofcode. 35 SuggestedHomework(cont’d)

• PROBLEM6:CHALLENGE(Makebrowniepoints withtheinstructor!:)

Thecomputerpicksarandomnumberbetween1and100. Makeausertrytoguessthecomputer’srandomnumber. Theprogramwillcontinueintheloopaslongastheuser hasn’tguessedthecorrectrandomnumber.

Iftheuser’snumberistoohigh,thecomputerwilltellthe user“Lower”andvice-versa.Aftertheuserguessesthe computer’srandomnumber,theprogramwillcongratulate theuserandterminate. 36 SuggestedHomework(cont’d)

Hint:TopickarandomnumberinPerl: $random_number=int(rand(1)*100)+1;

GoApplesoftBASIC!!! :) Hint:Theoverallstructureoftheprogramcouldgo somethinglikethis.

Pickarandomnumber $user_is_correct=0; #“0”meansincorrect; #weassumetheuseriswrong while($user_is_correct==0){ #while(user’sguessisnotcorrect) Getguessfromuser.Decideiftheguessiscorrectornotandmodify $user_is_correct.Giveuserfeedbackifhis/herguessistoohighor low. } Congratulatetheuserforwinning EndPartI