Perl | Loops (for, foreach, while, do...while, until, Nested loops)
文章推薦指數: 80 %
A while loop generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A ... Skiptocontent CoursesForWorkingProfessionalsDSAClasses(Live)SystemDesign(Live)JavaBackendDeveloper(Live)FullStack(Live)ExploreMoreLiveCoursesDSA(Self-Paced)SDETheory(Self-Paced)AllDevelopmentCourses(Self-Paced)ExploreMoreSelf-PacedCoursesForStudentsCompetitiveProgramming(Live)GATECourse2023(Live)DataScience(Live)ExploreMoreLiveCoursesDSA(Self-Paced)CIP(Self-Paced)JAVA/Python/C++(Self-Paced)ExploreMoreSelf-PacedCoursesSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#SQLScalaPerlGoLanguageKotlinWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesBusinessStudies(Class11th)BusinessStudies(Class12th)CSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersUPSCGeographyNotesHistoryNotesScience&Tech.NotesEthicsNotesPolityNotesEconomicsNotesUPSCPreviousYearPapersSSCCGLSSCCGLSyllabusGeneralStudiesEnglishReasoningSubjectwisePracticePapersPreviousYearPapersBankingExamsSBIClerkSBIClerkSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilitySBIClerkPracticePapersSBIPOSBIPOSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilityPreviousYearPapersSBIPOPracticePapersIBPSPOIBPSPO2022SyllabusEnglishNotesReasoningNotesPreviousYearPapersMockQuestionPapersIBPSClerkIBPSClerkSyllabusEnglishNotesPreviousYearPapersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWrite&EarnJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesWriteanArticleWriteArticlesPickTopicstowriteGuidelinestoWriteGetTechnicalWritingInternshipWriteanInterviewExperienceBasicsPerlProgrammingLanguageIntroductiontoPerlPerlInstallationandEnvironmentSetupinWindows,Linux,andMacOSPerl|BasicSyntaxofaPerlProgramHelloWorldPrograminPerlFundamentalsPerl|DataTypesPerl|BooleanValuesPerl|Operators|Set–1Perl|Operators|Set–2Perl|VariablesPerl|ModulesPackagesinPerlControlFlowPerl|DecisionMaking(if,if-else,Nested–if,if-elsifladder,unless,unless-else,unless-elsif)Perl|Loops(for,foreach,while,do…while,until,Nestedloops)Perl|given-whenStatementPerl|gotostatementArrays&ListsPerl|ArraysPerl|ArraySlicesPerl|Arrays(push,pop,shift,unshift)PerlListanditsTypesHashPerlHashPerl|HashOperationsPerl|MultidimensionalHashesScalarsPerl|ScalarsPerl|ComparingScalarsPerl|scalarkeywordStringsPerl|Quoted,InterpolatedandEscapedStringsPerl|StringOperatorsPerl|Stringfunctions(length,lc,uc,index,rindex)OOPConceptsObjectOrientedProgramming(OOPs)inPerlPerl|ClassesinOOPPerl|ObjectsinOOPsPerl|MethodsinOOPsPerl|ConstructorsandDestructorsPerl|MethodOverridinginOOPsPerl|InheritanceinOOPsPerl|PolymorphisminOOPsPerl|EncapsulationinOOPsRegularExpressionsPerl|RegularExpressionsPerl|OperatorsinRegularExpressionPerl|RegexCharacterClassesPerl|QuantifiersinRegularExpressionFileHandlingPerl|FileHandlingIntroductionPerl|OpeningandReadingaFilePerl|WritingtoaFilePerl|UsefulFile-handlingfunctionsCGIProgrammingPerl|CGIProgrammingPerl|FileUploadinCGIPerl|GETvsPOSTinCGIWriteanArticleWriteArticlesPickTopicstowriteGuidelinestoWriteGetTechnicalWritingInternshipWriteanInterviewExperienceBasicsPerlProgrammingLanguageIntroductiontoPerlPerlInstallationandEnvironmentSetupinWindows,Linux,andMacOSPerl|BasicSyntaxofaPerlProgramHelloWorldPrograminPerlFundamentalsPerl|DataTypesPerl|BooleanValuesPerl|Operators|Set–1Perl|Operators|Set–2Perl|VariablesPerl|ModulesPackagesinPerlControlFlowPerl|DecisionMaking(if,if-else,Nested–if,if-elsifladder,unless,unless-else,unless-elsif)Perl|Loops(for,foreach,while,do…while,until,Nestedloops)Perl|given-whenStatementPerl|gotostatementArrays&ListsPerl|ArraysPerl|ArraySlicesPerl|Arrays(push,pop,shift,unshift)PerlListanditsTypesHashPerlHashPerl|HashOperationsPerl|MultidimensionalHashesScalarsPerl|ScalarsPerl|ComparingScalarsPerl|scalarkeywordStringsPerl|Quoted,InterpolatedandEscapedStringsPerl|StringOperatorsPerl|Stringfunctions(length,lc,uc,index,rindex)OOPConceptsObjectOrientedProgramming(OOPs)inPerlPerl|ClassesinOOPPerl|ObjectsinOOPsPerl|MethodsinOOPsPerl|ConstructorsandDestructorsPerl|MethodOverridinginOOPsPerl|InheritanceinOOPsPerl|PolymorphisminOOPsPerl|EncapsulationinOOPsRegularExpressionsPerl|RegularExpressionsPerl|OperatorsinRegularExpressionPerl|RegexCharacterClassesPerl|QuantifiersinRegularExpressionFileHandlingPerl|FileHandlingIntroductionPerl|OpeningandReadingaFilePerl|WritingtoaFilePerl|UsefulFile-handlingfunctionsCGIProgrammingPerl|CGIProgrammingPerl|FileUploadinCGIPerl|GETvsPOSTinCGIPerl|Loops(for,foreach,while,do…while,until,Nestedloops)ViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 16Jun,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Loopinginprogramminglanguagesisafeaturewhichfacilitatestheexecutionofasetofinstructionsorfunctionsrepeatedlywhilesomeconditionevaluatestotrue.Loopsmaketheprogrammerstasksimpler.Perlprovidesthedifferenttypesoflooptohandletheconditionbasedsituationintheprogram.TheloopsinPerlare: forLoop“for”loopprovidesaconcisewayofwritingtheloopstructure.Unlikeawhileloop,aforstatementconsumestheinitialization,conditionandincrement/decrementinonelinetherebyprovidingashorter,easytodebugstructureoflooping.Syntax: for(initstatement;condition;increment/decrement) { #CodetobeExecuted }FlowChart: Aforloopworksonapredefinedflowofcontrol.Theflowofcontrolcanbedeterminedbythefollowing: initstatement:Thisisthefirststatementwhichisexecuted.Inthisstep,weinitializeavariablewhichcontrolstheloop.condition:Inthisstep,thegivenconditionisevaluatedandtheforlooprunsifitisTrue.ItisalsoanEntryControlLoopastheconditionischeckedpriortotheexecutionoftheloopstatements.Statementexecution:Oncetheconditionisevaluatedtotrue,thestatementsintheloopbodyareexecuted.increment/decrement:Theloopcontrolvariableischangedhere(incrementedordecremented)forupdatingthevariablefornextiteration.Looptermination:Whentheconditionbecomesfalse,theloopterminatesmarkingtheendofitslifecycle.Example: Perl#Perlprogramtoillustrate#theforloop #forloopfor($count=1;$count<=3;$count++){ print"GeeksForGeeks\n"}Output: GeeksForGeeks GeeksForGeeks GeeksForGeeks foreachLoopAforeachloopisusedtoiterateoveralistandthevariableholdsthevalueoftheelementsofthelistoneatatime.Itismajorlyusedwhenwehaveasetofdatainalistandwewanttoiterateovertheelementsofthelistinsteadofiteratingoveritsrange.Theprocessofiterationofeachelementisdoneautomaticallybytheloop.Syntax: foreachvariable { #CodetobeExecuted }FlowChart: Example: Perl#Perlprogramtoillustrate#theforeachloop #Array@data=('GEEKS','FOR','GEEKS'); #foreachloopforeach$word(@data){ print$word}Output: GEEKSFORGEEKS whileLoopAwhileloopgenerallytakesanexpressioninparenthesis.IftheexpressionisTruethenthecodewithinthebodyofwhileloopisexecuted.Awhileloopisusedwhenwedon’tknowthenumberoftimeswewantthelooptobeexecutedhoweverweknowtheterminationconditionoftheloop.Itisalsoknownasaentrycontrolledloopastheconditionischeckedbeforeexecutingtheloop.Thewhileloopcanbethoughtofasarepeatingifstatement.Syntax: while(condition) { #Codetobeexecuted }FlowChart: Example: Perl#Perlprogramtoillustrate#thewhileloop #whileloop$count=3;while($count>=0){ $count=$count-1; print"GeeksForGeeks\n";}Output: GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeksInfiniteWhileLoop:Whileloopcanexecuteinfinitetimeswhichmeansthereisnoterminatingconditionforthisloop.Inotherwords,wecansaytherearesomeconditionswhichalwaysremaintrue,whichcauseswhilelooptoexecuteinfinitetimesorwecansayitneverterminates. Example:BelowprogramwillprintthespecifiedstatementinfinitetimeandalsogivetheruntimeerrorasOutputLimitExceededononlineIDE Perl#Perlprogramtoillustrate#theinfinitewhileloop #infinitewhileloop#containingcondition1#whichisalwaystruewhile(1){ print"InfiniteWhileLoop\n";}Output: InfiniteWhileLoop InfiniteWhileLoop InfiniteWhileLoop InfiniteWhileLoop . . . . do….whileloopAdo..whileloopisalmostsameasawhileloop.Theonlydifferenceisthatdo..whilelooprunsatleastonetime.Theconditionischeckedafterthefirstexecution.Ado..whileloopisusedwhenwewantthelooptorunatleastonetime.Itisalsoknownasexitcontrolledloopastheconditionischeckedafterexecutingtheloop.Syntax: do{ #statementstobeExecuted }while(condition);FlowChart: Example: Perl#Perlprogramtoillustrate#do..whileLoop $a=10; #do..Whileloopdo{ print"$a"; $a=$a-1;}while($a>0);Output: 10987654321 untilloopuntilloopistheoppositeofwhileloop.Ittakesaconditionintheparenthesisanditonlyrunsuntiltheconditionisfalse.Basically,itrepeatsaninstructionorsetofinstructionuntiltheconditionisFALSE.Itisalsoentrycontrollerloopi.e.firsttheconditionischeckedthensetofinstructionsinsideablockisexecuted.Syntax: until(condition) { #Statementstobeexecuted }FlowChart: Example: Perl#PerlprogramtoillustrateuntilLoop $a=10; #untilloopuntil($a<1){ print"$a"; $a=$a-1;}Output: 10987654321 NestedLoopsAnestedloopisaloopinsidealoop.NestedloopsarealsosupportedbyPerlProgramming.Andallabove-discussedloopscanbenested.SyntaxfordifferentnestedloopsinPerl: Nestedforloop for(initstatement;condition;increment/decrement) { for(initstatement;condition;increment/decrement) { #CodetobeExecuted } } Nestedforeachloop foreachvariable_1(@array_1){ foreachvariable_2(@array_2) { #CodetobeExecuted } } Nestedwhileloop while(condition) { while(condition) { #CodetobeExecuted } } Nesteddo..whileloop do{ do{ #CodetobeExecuted }while(condition); }while(condition);Nesteduntilloop until(condition){ until(condition) { #CodetobeExecuted } } Example: Perl#Perlprogramtoillustrate#nestedwhileLoop $a=5;$b=0; #outerwhileloopwhile($a<7){ $b=0; #innerwhileloop while($b<7) { print"valueofa=$a,b=$b\n"; $b=$b+1; } $a=$a+1; print"Valueofa=$a\n\n";}Output: valueofa=5,b=0 valueofa=5,b=1 valueofa=5,b=2 valueofa=5,b=3 valueofa=5,b=4 valueofa=5,b=5 valueofa=5,b=6 Valueofa=6 valueofa=6,b=0 valueofa=6,b=1 valueofa=6,b=2 valueofa=6,b=3 valueofa=6,b=4 valueofa=6,b=5 valueofa=6,b=6 Valueofa=7 MyPersonalNotes arrow_drop_upSave LikePreviousPerl|DecisionMaking(if,if-else,Nested–if,if-elsifladder,unless,unless-else,unless-elsif)Next Perl|given-whenStatementRecommendedArticlesPage:20,Nov1913,Jun1913,Nov1920,Jun1825,Nov1902,Aug1802,May1903,Jul1930,May1929,Apr1926,Apr1928,Feb1913,Jul1820,Jun1820,Jun1825,Jun1818,Jul1826,Jun1828,Jun1803,Jul1803,Jul1803,Jul1806,Jul1812,Jul18ArticleContributedBy:GeeksforGeeksVotefordifficultyEasy Normal Medium Hard ExpertImprovedBy:varshagumber28ArticleTags:perl-basicsPerlPracticeTags:PerlReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNew ViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 15.7 迴圈控制
Perl 常見的迴圈有while、for、foreach、until,在每一種迴圈中,可以視情況,使用以下三種算符,來控制迴圈。 last 一次只能跳出一層迴圈語法:last 用例: $i=0;...
- 2Perl | Loops (for, foreach, while, do...while, until, Nested loops)
A while loop generally takes an expression in parenthesis. If the expression is True then the cod...
- 3控制結構(Control Structures) - Perl 程式設計 - 開源教學
Perl 沒有真正的真值(true value) 和偽值(false value),程式內部會自動判定值 ... my $n = 10; while ($n > 0) { print "Coun...
- 4Perl while 循环| 菜鸟教程
Perl while 循环Perl 循环while 语句在给定条件为true 时,重复执行语句或语句组。循环主体执行之前会先测试条件。 语法语法格式如下所示: while(condition) ...
- 5Perl 學習手札- 9. 再談控制結構 - Easun.org
不過如果能夠小心使用,這些控制程式流程的工具會是程式設計師重要的工具。所以我們就來看看除了之前提過的for,while,until,if等等各式各樣的流程控制之外, ...