Perl | Arrays (push, pop, shift, unshift) - GeeksforGeeks

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

Perl provides various inbuilt functions to add and remove the elements in an array. ... This function inserts the values given in the list at an ... 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|Arrays(push,pop,shift,unshift)ViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 25May,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Perlprovidesvariousinbuiltfunctionstoaddandremovetheelementsinanarray.   FunctionDescriptionpushInsertsvaluesofthelistattheendofanarraypopRemovesthelastvalueofanarrayshiftShiftsallthevaluesofanarrayonitsleftunshiftAddsthelistelementtothefrontofanarray pushfunction  Thisfunctioninsertsthevaluesgiveninthelistatanendofanarray.Multiplevaluescanbeinsertedseparatedbycomma.Thisfunctionincreasesthesizeofanarray.Itreturnsnumberofelementsinnewarray.  Syntax:push(Array,list)Example:  Perl#!/usr/bin/perl #Initializingthearray@x=('Java','C','C++'); #PrinttheInitialarrayprint"Originalarray:@x\n"; #Pushingmultiplevaluesinthearraypush(@x,'Python','Perl'); #Printingthearrayprint"Updatedarray:@x";Output:  Originalarray:JavaCC++ Updatedarray:JavaCC++PythonPerl   popfunction  Thisfunctionisusedtoremovethelastelementofthearray.Afterexecutingthepopfunction,sizeofthearrayisdecrementedbyoneelement.Thisfunctionreturnsundefiflistisemptyotherwisereturnsthelastelementofthearray.  Syntax:pop(Array)Example:  Perl#!/usr/bin/perl #Initializingthearray@x=('Java','C','C++'); #PrinttheInitialarrayprint"Originalarray:@x\n"; #Printsthevaluereturnedbypopprint"Valuereturnedbypop:",pop(@x); #Printsthearrayafterpopoperationprint"\nUpdatedarray:@x";Output:  Originalarray:JavaCC++ Valuereturnedbypop:C++ Updatedarray:JavaC   shiftfunction  Thisfunctionreturnsthefirstvalueinanarray,removingitandshiftingtheelementsofthearraylisttotheleftbyone.Shiftoperationremovesthevaluelikepopbutistakenfromthestartofthearrayinsteadoftheendasinpop.Thisfunctionreturnsundefifthearrayisemptyotherwisereturnsfirstelementofthearray.  Syntax:shift(Array)Example:  Perl#!/usr/bin/perl #Initializingthearray@x=('Java','C','C++'); #PrinttheInitialarrayprint"Originalarray:@x\n"; #Printsthevaluereturned#byshiftfunctionprint"Valuereturnedbyshift:",                        shift(@x); #Arrayaftershiftoperationprint"\nUpdatedarray:@x";Output:  Originalarray:JavaCC++ Valuereturnedbyshift:Java Updatedarray:CC++   unshiftfunction  Thisfunctionplacesthegivenlistofelementsatthebeginningofanarray.Therebyshiftingallthevaluesinanarraybyright.Multiplevaluescanbeunshiftusingthisoperation.Thisfunctionreturnsthenumberofnewelementsinanarray.  Syntax:unshift(Array,List)Example:  Perl#!/usr/bin/perl #Initializingthearray@x=('Java','C','C++'); #PrinttheInitialarrayprint"Originalarray:@x\n"; #Printsthenumberofelements#returnedbyunshiftprint"Noofelementsreturnedbyunshift:",                   unshift(@x,'PHP','JSP'); #Arrayafterunshiftoperationprint"\nUpdatedarray:@x";Output:  Originalarray:JavaCC++ Noofelementsreturnedbyunshift:5 Updatedarray:PHPJSPJavaCC++ MyPersonalNotes arrow_drop_upSave LikePreviousPerl|ArraySlicesNext PerlListanditsTypesRecommendedArticlesPage:02,Apr1915,Mar1928,Mar1928,Feb1913,Jun1913,Nov1928,Jun1809,Apr1922,Jul1918,Jun2002,Aug1802,May1903,Jul1930,May1929,Apr1926,Apr1928,Feb1913,Jul1820,Jun1820,Jun1820,Jun1825,Jun1818,Jul1826,Jun18ArticleContributedBy:rupanisweety@rupanisweetyVotefordifficultyEasy Normal Medium Hard ExpertImprovedBy:sweetytyArticleTags:Perl-ArraysPickedPerlPracticeTags:PerlReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNew  ViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?