Loop controls: next, last, continue, break - Perl Maven

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

next of Perl is the same as the continue in other languages and the last if ... my $nonempty = 0;; while (my $line = ) {; $counter++; ... Togglenavigation PerlMaven PerlTutorial Pro Login Register Books Typekeyword: Archive About Perltutorial Introduction InstallingandgettingstartedwithPerl TheHash-bangline,orhowtomakeaPerlscriptsexecutableonLinux PerlEditor HowtogetHelpforPerl? Perlonthecommandline CorePerldocumentationandCPANmoduledocumentation POD-PlainOldDocumentation DebuggingPerlscripts Scalars CommonWarningsandErrormessagesinPerl Prompt,readfromSTDIN,readfromthekeyboardinPerl AutomaticstringtonumberconversionorcastinginPerl Conditionalstatements,usingif,else,elsifinPerl BooleanvaluesinPerl Numericaloperators Stringoperators:concatenation(.),repetition(x) undef,theinitialvalueandthedefinedfunctionofPerl StringsinPerl:quoted,interpolatedandescaped Heredocuments,orhowtocreatemulti-linestringsinPerl Scalarvariables ComparingscalarsinPerl Stringfunctions:length,lc,uc,index,substr NumberGuessinggame whileloop ScopeofvariablesinPerl Short-circuitinbooleanexpressions Files HowtoexitfromaPerlscript? Standardoutput,standarderrorandcommandlineredirection Warningwhensomethinggoeswrong Whatdoesdiedo? WritingtofileswithPerl Appendingtofiles Openandreadfromtextfiles Don'tOpenFilesintheoldway ReadingandwritingbinaryfilesinPerl EOF-EndoffileinPerl tellhowfarhavewereadafile seek-movethepositioninthefilehandleinPerl slurpmode-readingafileinonestep ListsandArrays Perlforloopexplainedwithexamples PerlArrays Processingcommandlinearguments-@ARGVinPerl HowtoprocesscommandlineargumentsinPerlusingGetopt::Long AdvancedusageofGetopt::Longforacceptingcommandlinearguments Perlsplit-tocutupastringintopieces HowtoreadaCSVfileusingPerl? join Theyearof19100 ScalarandListcontextinPerl,thesizeofanarray Readingfromafileinscalarandlistcontext STDINinscalarandlistcontext SortingarraysinPerl Sortingmixedstrings UniquevaluesinanarrayinPerl ManipulatingPerlarrays:shift,unshift,push,pop ReversePolishCalculatorinPerlusingastack UsingaqueueinPerl Reverseanarray,astringoranumber TheternaryoperatorinPerl Loopcontrols:next,last,continue,break min,max,suminPerlusingList::Util qw-quoteword Subroutines SubroutinesandfunctionsinPerl PassingmultipleparameterstoafunctioninPerl VariablenumberofparametersinPerlsubroutines ReturningmultiplevaluesoralistfromasubroutineinPerl Understandingrecursivesubroutines-traversingadirectorytree Hashes HashesinPerl CreatingahashfromanarrayinPerl Perlhashinscalarandlistcontext exists-checkifakeyexistsinahash deleteanelementfromahash HowtosortahashinPerl? CountthefrequencyofwordsintextusingPerl RegularExpressions IntroductiontoRegexesinPerl5 Regexcharacterclasses Regex:specialcharacterclasses Perl5RegexQuantifiers trim-removingleadingandtrailingwhitespaceswithPerl Perl5RegexCheatsheet Shellrelatedfunctionality Whatare-e,-z,-s,-M,-A,-C,-r,-w,-x,-o,-f,-d,-linPerl? CurrentworkingdirectoryinPerl(cwd,pwd) RunningexternalprogramsfromPerlwithsystem qxorbackticks-runningexternalcommandandcapturingtheoutput Howtoremove,copyorrenameafilewithPerl Readingthecontentofadirectory Traversingthefilesystem-usingaqueue CPAN DownloadandinstallPerl InstallingaPerlModulefromCPANonWindows,LinuxandMacOSX Howtochange@INCtofindPerlmodulesinnon-standardlocations Howtoaddarelativedirectoryto@INC ExamplesforusingPerl HowtoreplaceastringinafilewithPerl HowtoreadanExcelfileinPerl HowtocreateanExcelfilewithPerl? SendingHTMLe-mailusingEmail::Stuffer Perl/CGIscriptwithApache2 JSONinPerl SimpleDatabaseaccessusingPerlDBIandSQL ReadingfromLDAPinPerlusingNet::LDAP Commonwarningsanderrormessages Globalsymbolrequiresexplicitpackagename VariabledeclarationinPerl Useofuninitializedvalue BarewordsinPerl Name"main::x"usedonlyonce:possibletypoat... Unknownwarningscategory Can'tusestring(...)asanHASHrefwhile"strictrefs"inuseat... SymbolicreferencesinPerl Can'tlocate...in@INC Scalarfoundwhereoperatorexpected "my"variablemasksearlierdeclarationinsamescope Can'tcallmethod...onunblessedreference Argument...isn'tnumericinnumeric... Can'tlocateobjectmethod"..."viapackage"1"(perhapsyouforgottoload"1"?) Uselessuseofhashelementinvoidcontext Uselessuseofprivatevariableinvoidcontext readline()onclosedfilehandleinPerl Possibleprecedenceissuewithcontrolflowoperator Scalarvalue...betterwrittenas... substroutsideofstringat... Haveexceededthemaximumnumberofattempts(1000)toopentempfile/dir Useofimplicitsplitto@_isdeprecated... Other MultidimensionalarraysinPerl MultidimensionalhashesinPerl MinimalrequirementtobuildasaneCPANpackage Statementmodifiers:reversedifstatements Whatisautovivification? FormattedprintinginPerlusingprintfandsprintf Loopcontrols:next,last,continue,break next last continue break Prev Next InPerlthereare3loopcontrolkeywords.Thetwocommonlyusedarenextandlastandthereisathirdwhichisrarelyusedcalledredo. Inmostoftheotherlanguagestherespectivekeywordsarecontinueandbreak. nextofPerlisthesameasthecontinueinotherlanguagesandthelastifPerlisthesameasthebreakofotherlanguages. redoprobablydoesnothaveitscounterpart. nextwilljumptotheconditionandifitistruePerlwillexecutethenextiteration. lastwillquitetheloop. Takealookatthisexample.Thisscriptwillcountthenumberofnon-emptyrowsinafileuntilitencounters__END__ortheendoffile. examples/loop_control.pl #!/usr/bin/perl usestrict; usewarnings; my$filename=shiftordie"Usage:$0FILENAME\n"; main($filename); submain{ my($file)=@_; openmy$fh,'){ $counter++; chomp$line; if($lineeq"__END__"){ last;#endprocessingfile } if($lineeq""){ $empty++; next;#don'tprocessemptyrows,gotonextline } print"Process'$line'\n"; $nonempty++; ###nextjumpshere### } ###lastjumpshere### print"Numberofemptyrows$emptyandnonemptyrows:$nonemptyoutofatotalof$counter\n" } Giventhisinputfile: examples/loop_control.txt Firstline Lineafteremptyline Anothertextline __END__ Sometexthere thatwon'tbeprinted theoutputwillbethis: Process'Firstline' Process'Lineafteremptyline' Process'Anothertextline' Numberofnonemptyrows:3outofatotalof6 next Thenextkeywordisusuallyusedwhenweduringouriterationwehaveanconditioninsidetheloopandifthatconditionismatched(orfaildtomatch)thenwewouldliketoendthecurrentiterationandgotothenextone.Forexampleifwearelookingforastringthatstartswith"DNA:"andthenhasaDNAinitwithsomecomplexrule,wemightfirstcheckifthecurrentrowstartswith"DNA:".Ifitdoesnotthenthereisnopointinfurtherinvestigatingthecurrentstringandwecangotothenextiteration. last OntheotherhandifwefoundtheDNAwewerelookingforwemightstopthewholesearchifweareonlyinterestedinthefirstsuchDNA.Inthiscasecallinglastwillbreakusoutfromthecurrentloopsavingalotoftimebynotiteratingovertherestofthevalues. InthisexamplewewerelookingforaDNAwitha3-characterrepetition. examples/find_dna.pl #!/usr/bin/perl usestrict; usewarnings; my$file=shiftordie"Usage:$0FILENAME\n"; openmy$fh,'){ chomp$line; my($dna)=$line=~/^DNA:(.*)/; if(not$dna){ next;#skiprowswithoutDNA:atthebeginning } print"Checking$dna\n"; if($dna=~/([ACTG]{3}).*\1/){ $interesting_dna=$dna; last;#gottotheendoftheloop,skiprestofthefile } } if($interesting_dna){ print"FirstinterestingDNA:$interesting_dna\n"; } Thisisourverylimitedinputfile: examples/find_dna.txt human: DNA:ACTGGTATTA mouse: DNA:ACTGTAACTG elephant: DNA:AACCTTGGAA Theresultingoutputlookslikethis: CheckingDNA:ACTGGTATTA CheckingDNA:ACTGTAACTG FirstinterestingDNA:ACTGTAACTG ItskippedallthelinesthatdidnotstartwithDNA:andonceitfoundamatch(inthe2ndDNA)itstoppedlookingskippingalltheotherlines. redo Callingredowillexecutethecurrentiterationagainwithoutcheckingthecondition.Idon'trecallusingit solet'snotgetintoitnow. Prev Next Writtenby GaborSzabo Publishedon2021-01-20 Comments Inthecomments,pleasewrapyourcodesnippetswithin

tagsandusespacesforindentation.
commentspoweredbyDisqus
Ifyouhaveanycommentsorquestions,feelfreetopostthemonthesourceofthispageinGitHub.SourceonGitHub.
Commentonthispost
Author:GaborSzabo
GaborwhorunsthePerlMavensitehelpscompaniessetuptestautomation,CI/CD
ContinuousIntegrationandContinuousDeploymentandotherDevOpsrelated
systems.
GaborcanhelprefactoryouroldPerlcode-base.
HerunsthePerlWeeklynewsletter.
ContactGaborifyou'dliketohirehisservice.
BuyhiseBooksorifyoujustwouldliketosupporthim,doitviaPatreon.
BooleanvaluesinPerl



請為這篇文章評分?