how to break out of a loop in Perl | alvinalexander.com

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

In many programming languages you use the break operator to break out of a loop like this, but in Perl you use the last operator to break out of ... 2021cookbook    #1newrelease! Perlloop-howtobreakoutofaloopinPerl ByAlvinAlexander.Lastupdated:June4,2016 PerlloopbreakFAQ: HowdoI breakoutofaPerlloop? Problem:You'rewritingsomePerlloopcode(for,foreach,orwhile),andyouhaveaconditionwhereyouneedtobreakoutofyourloopearly,andyouquicklyfindoutthatPerldoesn'thavea'break'operator. ThePerl"break"statement Inmanyprogramminglanguagesyouusethebreakoperatortobreakoutofalooplikethis,butinPerlyouusethelastoperatortobreakoutofaloop,likethis: last; WhileusingthePerllastoperatorinsteadoftheusualbreakoperatorseemsalittleunusual,itcanmakeforsomereadablecode,aswe'llseenext. Aforloopexamplewithlast Here'saPerlbreak/lastexampleIjustpulledoutofanactualscript.Isimplifiedthisalittlebit,butinshort,thisforeachloopwasintendedtoletmepush10itemsontoanarraynamed@tags,andthenbreakoutoftheloopatthatpoint: my$counter=1; foreach$foo(sort{$importHash{$b}<=>$importHash{$a}}(keys%importHash)) { #pushthestring$fooontothe@tagsarray push@tags,$foo; #breakoutofourperlloopwhenthecounterreaches10 lastif($counter++==10); } Ireallylikethelast/ifsyntaxshownabove,butIshouldnotethatyoucanalsousethePerllastoperatorinatypicalif/thenstatementifyouprefer,likethis: if(SOME_TEST_CONDITION) { #breakoutofourperlloop last; } Related-howtoskipanelementinaPerlloop Onarelatednote,ifyoujustneedtoskipoverthecurrentloopiteration--andstayinyourPerllooptoworkonthenextelement--justusethePerlnextoperator,likethis: if(SOME_TEST_CONDITION) { next; } Formoreinformation,here'salinktomyPerlforloop'next'tutorial.Otherwise,I hopethisPerlbreak/lastexamplehasbeenhelpful. perl break forloop next perl perlloop last Perlnextoperator-forloopandifstatementexamples Perlbestpractice:preferforeachtofor APerlarrayandforeachexample Perlforloop-Howtodosomethingforeachelementinanarray Howtoexcludecertainelementsinanarraywithpatternmatching booksi’vewritten (Almost)FunctionalProgramming SomeofShinzenYoung’ssayingsinthefirstcorelessonsoftheBrightmindapp LearnScala3TheFastWay!(BestwaytolearnScala!) FunctionalProgramming,Simplified(aScalabook) HomagetoHaskellandFunctionalProgramming



請為這篇文章評分?