Perl next operator - for loop and if statement examples
文章推薦指數: 80 %
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
延伸文章資訊
- 1What are the Perl equivalents of return and continue keywords ...
return is the equivalent of return. next is the equivalent of continue. last is the equivalent of...
- 2Perl foreach loops
A foreach loop runs a block of code for each element of a list. No big whoop, “perl foreach” cont...
- 3Loop controls: next, last, continue, break - Perl Maven
In Perl there are 3 loop control keywords. The two commonly used are next and last and there is a...
- 4精簡扼要的Perl 課程講義(三):迴圈與控制結構 - G. T. Wang
next 跳到這裡 } # last 跳到這裡繼續執行 # 註:next, last 與redo 皆可用在for,foreach,while 與until 等迴圈。 # (7) if # (A)...
- 5Perl next operator - for loop and if statement examples
When you're in a Perl for loop (iterating over an array or hash), and you want to move on to the ...