Perl next operator - for loop and if statement examples

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

When you're in a Perl for loop (iterating over an array or hash), and you want to move on to the next element in your array or hash, just use ... 2021cookbook    #1newrelease! Perlnextoperator-forloopandifstatementexamples ByAlvinAlexander.Lastupdated:June4,2016 PerlnextloopFAQ: CanyoudemonstratehowtousethePerlnextoperatorinaforloop? Problem:You'rewritingcodeforaPerlloop,andyouneedtowritesomelogictoskipoverthecurrentelementintheloop,andmoveontothenextloopelement. ThePerlloopnextoperator Whenyou'reinaPerlforloop(iteratingoveranarrayorhash),andyouwanttomoveontothenextelementinyourarrayorhash,justusethePerlnextoperator,likethis: for(@array) { if(SOME_TEST_CONDITION) { #moveontothenextloopelement next; } #morecodehere... } MorePerlnextexamples YoucanseesomedecentexamplesofthePerlnextoperatorinthefollowingcode.InthecodejustbeforethisforloopIhadjustreadalltherecordsofaPerlscriptintoanarraynamed@records,andinthePerlforloopshownbelowI'mskippingoverallthestringsI'mnotreallyinterestedin: for(@records) { #skipblanklines nextif/^[\t]*$/; #skipcommentlines nextif/#/; #skipprintinglines nextif/print/; nextif/printf/; #muchmorecodehere... } Perlnextoperator-Summary Asyoucansee,youusethePerlnextoperatortoskiptothenextelementinaPerlforloop,andthereareatleasttwowaystousethenextoperator,asshownintheexamplesabove:insideanifstatement,orbeforeanifstatement. Related-howtobreakoutofaPerlforloop Inarelatednote,youcanbreakoutofaPerlforloopusingthePerllastoperator,likethis: if(SOME_TEST_CONDITION) { last; } ThePerllastoperatorworksjustlikethebreakoperatorinotherlanguages,breakingoutoftheloopwhenthelastoperatorisencountered.YoucanreadmoreaboutthelastoperatorinmyPerlforloopbreaktutorial. perl else forloop if next perl perlloop last continue Perlloop-howtobreakoutofaloopinPerl Perlcomparisonoperators Perl‘equals’FAQ:WhatistrueandfalseinPerl? Perlif,else,elsif("elseif")syntax HowtousethePerlternaryoperator booksi’vewritten (Almost)FunctionalProgramming SomeofShinzenYoung’ssayingsinthefirstcorelessonsoftheBrightmindapp LearnScala3TheFastWay!(BestwaytolearnScala!) FunctionalProgramming,Simplified(aScalabook) HomagetoHaskellandFunctionalProgramming



請為這篇文章評分?