Perl - difference between 'next' and 'continue'? - Stack Overflow

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

The continue keyword can be used after the block of a loop. The code in the continue block is executed before the next iteration (before the loop condition ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam StackOverflowforTeamsismovingtoitsowndomain!Whenthemigrationiscomplete,youwillaccessyourTeamsatstackoverflowteams.com,andtheywillnolongerappearintheleftsidebaronstackoverflow.com. Checkyouremailforupdates. Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Perl-differencebetween'next'and'continue'? AskQuestion Asked 10years,2monthsago Modified 1year,7monthsago Viewed 42ktimes 27 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. QuickPerlquestion:whengoingthroughaloop(sayawhileloop),whatisthedifferencebetweenanextandcontinuecommand?Ithoughtbothjustskiptothenextiterationoftheloop. perlloops Share Improvethisquestion Follow askedAug22,2012at21:41 JDSJDS 15.7k4646goldbadges152152silverbadges216216bronzebadges 1 7 Shortanswer.PerlnextislikeJavaandmostotherlanguages'continue.Useanamedlabelonyourloop.Perlcontinuewouldrarelybeused. – Jess Mar19,2013at13:31 Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 22 Thecontinuekeywordcanbeusedaftertheblockofaloop.Thecodeinthecontinueblockisexecutedbeforethenextiteration(beforetheloopconditionisevaluated).Itdoesnotaffectthecontrol-flow. my$i=0; when(1){ print$i,"\n"; } continue{ if($i<10){ $i++; }else{ last; } } Isalmostequivalentto foreachmy$i(0..10){ print$i,"\n"; } Thecontinuekeywordhasanothermeaninginthegiven-whenconstruct,Perl'sswitch-case.Afterawhenblockisexecuted,Perlautomaticallybreaksbecausemostprogramsdothatanyway.Ifyouwanttofallthroughtothenextcasesthecontinuehastobeused.Here,continuemodifiesthecontrolflow. given("abc"){ when(/z/){ printqq{Founda"z"\n}; continue; } when(/a/){ printqq{Founda"a"\n}; continue; } when(/b/){ printqq{Founda"b"\n}; continue; } } Willprint Founda"a" Founda"b" Thenextkeywordisonlyavailableinloopsandcausesanewiterationincl.re-evaluationoftheloopcondition.redojumpstothebeginningofaloopblock.Theloopconditionisnotevaluated. Share Improvethisanswer Follow editedAug22,2012at21:55 answeredAug22,2012at21:46 amonamon 56.4k22goldbadges8686silverbadges147147bronzebadges 5 1 Hi,couldyougiveanexamplecontrastingthecontinueandnext? – JDS Aug22,2012at21:50 It'snottruethatnextis"onlyavailableinloops".Youcanactuallynextoutofanon-loopblockandPerlwon'tstopyou;it'sjustnotveryusefulorverykindtothereaderofyourcode. – hobbs Aug23,2012at3:54 @hobbsOfcourse,butonlyiftheblockisnamed.if(1){next}failsalthoughthereisasyntacticblock.subfoo{next}foo()failsalthoughthereisasyntacticblock.OnlynamedblockslikeFOO:{next}work.OrdidImisssomething? – amon Aug23,2012at10:05 1 @amonItdoesn'thavetobenamed,itjusthastobeabareblock,notbelongingtoanif.for(1..3){print"a";{next;print"b"}print"c"}prints"acacac"not"aaa". – hobbs Aug23,2012at19:16 3 Thereisatypointhefirstcodeblock,Isuspectyoumentwhile(1){..notwhen(1){... – ArsenyNerinovsky Jul30,2016at19:14 Addacomment  |  2 Executionofnextstatmentwillskipexecutingrestofthestatmentsintheloopforthatpirticulariteration. Statmentsinthecontinueblockwillexecuteforeachandeveryiteration,irrespectiveofloopexecutedasusualorloopneedtoterminatethepirticulariterationbyencountringthenextstatment. examplewithoutcontinueblock: my$x=0; while($x<10) { if($x%2==0) { $x++;#incrementingxfornextloopwhentheconditioninsidetheifissatisfied. next; } print($x."\n"); $x++;#incrementingxforthenextloop } Inaboveexampleincrementationofxneedtobewritten2times.Butifweusecontinuestatmentwhichcanholdthestatmentsthatneededtobeexecutedallthetimeswecanincrementxonlyonetimeinsidecontinueloop. my$x=0; while($x<10) { if($x%2==0) { next; } print($x."\n"); } continue { $x++; } outputinboththecasesare1,3,5,7,9 Share Improvethisanswer Follow answeredMar11,2021at8:16 SuneeldattaKolipakulaSuneeldattaKolipakula 21711silverbadge66bronzebadges 0 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedperlloopsoraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Related 853 C#loop-breakvs.continue 825 WhatisthedifferencebetweenrangeandxrangefunctionsinPython2.X? 367 HowdoIskipaniterationofa`foreach`loop? 260 What'sthedifferencebetweenPerl'sbackticks,system,andexec? 366 Howtoretryafterexception? 223 "for"vs"each"inRuby 371 Declaringvariablesinsideloops,goodpracticeorbadpractice? 2233 HowdoesPHP'foreach'actuallywork? 674 WaystoiterateoveralistinJava HotNetworkQuestions WhereisthisparkinMontreal,withautumncolortreesandpond? Isthetermשָׁלֹום(peace)inIsaiah53:5usuallymisunderstood? HexproofandAetherStorm Howdopropellanttransfertechnologieswork? Zeropaddingversuszerostuffing UnderwhatauthoritycantheUSmakefederalreservenoteslegaltender? WhatcanIdoaboutplayerswho"cheat"whenansweringtheendofsessionquestions? Minimumrotationtogetthemaximumvalue HowdoIlabelatablelikethis? Whatisthemostefficientwaytoget110Vfrom220Vsingle-phasewiring? TeXpointcommand Mylibrarymembershipnumber Plotasequenceoffunctionsinoneplot Howtoobtainaminor'spassportwithanabsentparent StudentsdoubttheusefulnessofthePresentPerfecttenses Robbersinastandoff WhyisthePassivevoiceof"einladen"usedwith"sein"andnotwerden? Addaclosingtag Whatisanaxiomatizationoftheequality-freetheoryofantisymmetricrelations? DoGFI/GFCIoutletshaveapotentialtodamageNespressomachines(andcoffeemachines?) Withoutwind,wouldaplanegostraightifthepilotletgoofthecontrols? Ifform8606isnotrequiredtosubmitforjustRothIRAcontributions?HowdoesIRSenforcethelimit? Whywouldatechnologicallyadvancedsocietyusehumancontrollerstodirectspaceshiptraffic? Whattodoafterapuremathacademicpath? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?