Manipulating Perl arrays: shift, unshift, push, pop - Perl Maven
文章推薦指數: 80 %
If you imagine the array starting on the left hand side, the shift function will move the whole array one unit to the left. The first element will "fall ... 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 ManipulatingPerlarrays:shift,unshift,push,pop array shift unshift push pop Prev Next Aswellasallowingdirectaccesstoindividualarrayelements, Perlalsoprovidesvariousotherinterestingwaystodealwitharrays. Inparticular,therearefunctionsthatmakeitveryeasyandefficient touseaPerlarrayasastackorasaqueue. pop Thepopfunctionwillremoveandreturnthelastelementofanarray. Inthisfirstexampleyoucanseehow,givenanarrayof3elements,thepopfunction removesthelastelement(theonewiththehighestindex)andreturnsit. my@names=('Foo','Bar','Baz'); my$last_one=pop@names; print"$last_one\n";#Baz print"@names\n";#FooBar Inthespecialcaseoftheoriginalarraybeingempty,thepopfunction willreturnundef. push Thepushfunctioncanaddoneormorevaluestotheendofanarray. (Well,itcanalsoadd0values,butthat'snotveryuseful,isit?) my@names=('Foo','Bar'); push@names,'Moo'; print"@names\n";#FooBarMoo my@others=('Darth','Vader'); push@names,@others; print"@names\n";#FooBarMooDarthVader Inthisexampleweoriginallyhadanarraywithtwoelements. Thenwepushedasinglescalarvaluetotheendandourarray gotextendedtoa3-elementarray. Inthesecondcalltopush,wepushedthecontentofthe@others arraytotheendofthe@namesarray,extendingittoa5-elementarray. shift Ifyouimaginethearraystartingonthelefthandside, theshiftfunctionwillmovethewholearrayoneunittotheleft. Thefirstelementwill"falloff"thearrayandbecomethefunction'sreturnvalue. (Ifthearraywasempty,shiftwillreturnundef.) Aftertheoperation,thearraywillbeoneelementshorter. my@names=('Foo','Bar','Moo'); my$first=shift@names; print"$first\n";#Foo print"@names\n";#BarMoo Thisisquitesimilartopop,butitworksonthelowerendofthearray. unshift Thisistheoppositeoperationofshift.unshiftwill takeoneormorevalues(oreven0ifthat'swhatyoulike)andplaceitatthe beginningofthearray,movingalltheotherelementstotheright. Youcanpassitasinglescalarvalue,whichwillbecomethe firstelementofthearray.Or,asinthesecondexample,youcanpassasecond arrayandthentheelementsofthissecondarray(@othersinourcase) willbecopiedtothebeginningofthemainarray(@namesinourcase) movingtheotherelementstohigherindexes. my@names=('Foo','Bar'); unshift@names,'Moo'; print"@names\n";#MooFooBar my@others=('Darth','Vader'); unshift@names,@others; print"@names\n";#DarthVaderMooFooBar Prev Next Writtenby GaborSzabo Publishedon2013-02-06 Comments Inthecomments,pleasewrapyourcodesnippetswithin
tagsandusespacesforindentation. commentspoweredbyDisqus Ifyouhaveanycommentsorquestions,feelfreetopostthemonthesourceofthispageinGitHub.SourceonGitHub. Commentonthispost Author:GaborSzabo GaborwhorunsthePerlMavensitehelpscompaniessetuptestautomation,CI/CD ContinuousIntegrationandContinuousDeploymentandotherDevOpsrelated systems. GaborcanhelprefactoryouroldPerlcode-base. HerunsthePerlWeeklynewsletter. ContactGaborifyou'dliketohirehisservice. BuyhiseBooksorifyoujustwouldliketosupporthim,doitviaPatreon. English Français Italiano Português 简体中文 aboutthetranslations undef,theinitialvalueandthedefinedfunctionofPerl延伸文章資訊
- 1shift - Perldoc Browser
Starting with Perl 5.14, an experimental feature allowed shift to take a scalar expression. This ...
- 2Perl | shift() Function - GeeksforGeeks
shift() function in Perl returns the first value in an array, removing it and shifting the elemen...
- 3Perl中shift函数用法 - CSDN博客
数组也被改变,其第一个元素被弹出。 如果没有array,直接给变量赋值shift. @ARGV: perl 命令行参数. 当运行perl脚本的时候,从 ...
- 4perl程序中shift的用法 - 百度知道
看到有些perl程序写子程序submysub{my$pk=shift;}这里新定义的变量$pk,为什么要直接用shift,这里的shift起到什么作用?我只知道shift是从数组开头移除 ...
- 5perl shift()函數 - 極客書
perl shift()函數例子,shift()函數實例代碼- 返回在一個數組中的第一個值,刪除和移位到左邊的元素數組列表一個位置。 語法. shift ( [ARRAY] ). shift. ...