Perl while Loop - Perl Tutorial
文章推薦指數: 80 %
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
延伸文章資訊
- 1Perl while Loop - Perl Tutorial
The Perl while loop statement executes a code block repeatedly as long as the test condition rema...
- 2Perl while Loop - Tutorialspoint
Perl while Loop, A while loop statement in Perl programming language repeatedly executes a target...
- 3Perl的基本語法
純量變數是Perl裡最基本的一種資料型態,它可以代表一個字元、字串、整數、甚至浮點數, ... 下面是一個十分精簡的寫法,和while($_=<FILE>){print "$_";} 是等效的。
- 4[PERL] 09-迴圈@新精讚
使用foreach列出陣列內容; 使用foreach列出雜湊內容. 無限迴圈. 迴圈的控制. next; last; redo. 迴圈和一般程式語言大同小異,主要有幾種. while.
- 5while - Perldoc Browser
The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please con...