Perl while Loop - Perl Tutorial

文章推薦指數: 80 %
投票人數:10人

The Perl while loop statement executes a code block repeatedly as long as the test condition remains true. The test condition is checked at the beginning of ... SkiptocontentHome»PerlwhileLoopSummary:inthistutorial,you’lllearnhowtousePerlwhileloopstatementtoexecuteacodeblockrepeatedlybasedonaconditioncheckedatthebeginningofeachiteration.IntroductiontoPerlwhileloopstatementThePerlwhileloopstatementexecutesacodeblockrepeatedlyaslongasthetestconditionremains true.Thetestconditionischeckedatthebeginningofeachiteration.ThefollowingillustratesthesyntaxofthePerlwhileloopstatement:while(condition){ #codeblock }Codelanguage:Perl(perl)Iftheconditionevaluatestotrue,thecodeblockinsidewhileloopexecutes.Atthebeginningofeachiteration,theconditionisreevaluated.Theloopisterminatediftheconditionevaluatestofalse.Atsomepointintheloop,youhavetochangesomevariablesthatmaketheconditionfalsetostoptheloop.Otherwise,youwillhaveanindefiniteloopthatmakesyourprogramexecuteuntilthestackoverflowerroroccurs.Thewhileloopstatementhasanoptionalblock:continue,whichexecutesaftereachcurrentiteration.Inpractice,thecontinueblockisrarelyused.while(condition){ #codeblock } continue{ #continuecodeblock }Codelanguage:Perl(perl)Thefollowingflowchartillustrateshowthewhileloopstatementworks:Ifyouwanttoexecuteacodeblockaslongastheconditionisfalse,youcanuseuntilstatement.Incaseyouwanttochecktheconditionattheendofeachiteration,youusethedo…whileordo…untilstatementinstead.Tocontrolloop,youusenextandlaststatements.PerlwhileloopexampleThefollowingexampledemonstrateshowtousethewhileloopstatementtodeveloptheHappyNewYearCountDownprogram:#!/usr/bin/perl usewarnings; usestrict; my$counter=10; while($counter>0){ print("$counter\n"); #countdown $counter--; #pauseprogramfor1second sleep(1); if($counter==0){ print("HappyNewYear!\n"); } }Codelanguage:Perl(perl)Let’sexaminethecodeaboveinmoredetail:First,declarea$countervariableandsetitsvalueto10.Next,putaconditiontomakesurethatthevalueof$counterisgreaterthanzerobeforeenteringintotheloop.Then,displayedthe$counteranddecreaseditscurrentvalueofone.Weusedthe sleep() functiontopausetheprogramforasecondineachiteration.Afterthat,usetheifstatementtocheckif$counter iszerotoprintthe“HappyNewYear”message.Thecodeblockinsidetheloopexecutes10timesbeforethe$counterissettozero.Finally,aftereachiteration,the$counter isdecreasinganditsvalueissetzeroatthe10thiteration.Perlterminatedtheloop.Thefollowingshowstheoutputoftheprogram:10 9 8 7 6 5 4 3 2 1 HappyNewYear!Codelanguage:PHP(php)Perlwhileloopwithdiamondoperator<>Youoftenusethewhileloopstatementwiththediamondoperator<>togetuser’sinputfromthecommandline.Forexample:#!/usr/bin/perl usewarnings; usestrict; my$num; my@numbers=(); print"Enternumbers,eachperline:\n"; print"ctrl-z(windows)orctrl-d(Linux)toexit\n>"; while(my$input=<>){ print(">"); chomp$input; $num=int($input); push(@numbers,$num); } print"Youentered:@numbers\n";Codelanguage:Perl(perl)Howitworks.First,assigntheuser’sinputintothe $inputvariableusingthediamondoperator(<>).Becauseitdoesn’tspecifyanyfilehandleforthediamondoperator,Perlchecksthespecialarray@ARGV,whichisemptyinthiscase,henceinstructsthediamondoperatortoreadfromSTDINi.e.,fromthekeyboard.Second,removethenewlinecharacterfromthe$input variableusingthechomp()functionandconvert$inputtoaninteger.Third,addtheintegerintothe@numberarray.Thefollowingistheoutputoftheprogram:Enternumbers,eachperline: ctrl-z(windows)orctrl-d(Linux)toexit >1 >3 >2 >6 >7 >^Z Youentered:13267Codelanguage:Perl(perl)PerlwhileloopstatementmodifierFirst,let’stakealookatthefollowingexample:#!/usr/bin/perl usewarnings; usestrict; my$i=5; print($i--,"\n")while($i>0);Codelanguage:Perl(perl)Inthisexample,thewhileloopstatementisplacedafteranotherstatement.However,Perlevaluatesthestatementsfromrighttoleft.ItmeansthatPerlevaluatestheconditioninthewhilestatementatthebeginningofeachiteration.Youusethewhileloopstatementmodifieronlyifyouhaveonestatementtoexecuterepeatedlybasedonaconditionliketheaboveexample.Inthistutorial,you’velearnedaboutthePerlwhileloopstatementthatexecutesacodeblockrepeatedlyaslongasatestconditionremains true.Wasthistutorialhelpful?YesNoPreviouslyPerlforLoopUpNextPerldowhileSearchfor:GettingStartedBasicPerlTutorialPerlI/O



請為這篇文章評分?