Perl | Loops (for, foreach, while, do...while, until, Nested loops)

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

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



請為這篇文章評分?