Perl - Arrays - Tutorialspoint
文章推薦指數: 80 %
Adding and Removing Elements in Array. Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus PerlBasics Perl-Home Perl-Introduction Perl-Environment Perl-SyntaxOverview Perl-DataTypes Perl-Variables Perl-Scalars Perl-Arrays Perl-Hashes Perl-IF...ELSE Perl-Loops Perl-Operators Perl-Date&Time Perl-Subroutines Perl-References Perl-Formats Perl-FileI/O Perl-Directories Perl-ErrorHandling Perl-SpecialVariables Perl-CodingStandard Perl-RegularExpressions Perl-SendingEmail PerlAdvanced Perl-SocketProgramming Perl-ObjectOriented Perl-DatabaseAccess Perl-CGIProgramming Perl-Packages&Modules Perl-ProcessManagement Perl-EmbeddedDocumentation Perl-FunctionsReferences PerlUsefulResources Perl-QuestionsandAnswers Perl-QuickGuide Perl-UsefulResources Perl-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho Perl-Arrays Advertisements PreviousPage NextPage PerlOnlineTraining 46Lectures 4.5hours DeviKillada MoreDetail COMPLETEPERLProgramming 11Lectures 1.5hours HarshitSrivastava MoreDetail PerlforBeginners:LearnAtoZofPerlScriptingHands-on 30Lectures 6hours TELCOMAGlobal MoreDetail Anarrayisavariablethatstoresanorderedlistofscalarvalues.Arrayvariablesareprecededbyan"at"(@)sign.Torefertoasingleelementofanarray,youwillusethedollarsign($)withthevariablenamefollowedbytheindexoftheelementinsquarebrackets. Hereisasimpleexampleofusingthearrayvariables− LiveDemo #!/usr/bin/perl @ages=(25,30,40); @names=("JohnPaul","Lisa","Kumar"); print"\$ages[0]=$ages[0]\n"; print"\$ages[1]=$ages[1]\n"; print"\$ages[2]=$ages[2]\n"; print"\$names[0]=$names[0]\n"; print"\$names[1]=$names[1]\n"; print"\$names[2]=$names[2]\n"; Herewehaveusedtheescapesign(\)beforethe$signjusttoprintit.OtherPerlwillunderstanditasavariableandwillprintitsvalue.Whenexecuted,thiswillproducethefollowingresult− $ages[0]=25 $ages[1]=30 $ages[2]=40 $names[0]=JohnPaul $names[1]=Lisa $names[2]=Kumar InPerl,ListandArraytermsareoftenusedasifthey'reinterchangeable.Butthelististhedata,andthearrayisthevariable. ArrayCreation Arrayvariablesareprefixedwiththe@signandarepopulatedusingeitherparenthesesortheqwoperator.Forexample− @array=(1,2,'Hello'); @array=qw/Thisisanarray/; Thesecondlineusestheqw//operator,whichreturnsalistofstrings,separatingthedelimitedstringbywhitespace.Inthisexample,thisleadstoafour-elementarray;thefirstelementis'this'andlast(fourth)is'array'.Thismeansthatyoucanusedifferentlinesasfollows− @days=qw/Monday Tuesday ... Sunday/; Youcanalsopopulateanarraybyassigningeachvalueindividuallyasfollows− $array[0]='Monday'; ... $array[6]='Sunday'; AccessingArrayElements Whenaccessingindividualelementsfromanarray,youmustprefixthevariablewithadollarsign($)andthenappendtheelementindexwithinthesquarebracketsafterthenameofthevariable.Forexample− LiveDemo #!/usr/bin/perl @days=qw/MonTueWedThuFriSatSun/; print"$days[0]\n"; print"$days[1]\n"; print"$days[2]\n"; print"$days[6]\n"; print"$days[-1]\n"; print"$days[-7]\n"; Thiswillproducethefollowingresult− Mon Tue Wed Sun Sun Mon Arrayindicesstartfromzero,sotoaccessthefirstelementyouneedtogive0asindices.Youcanalsogiveanegativeindex,inwhichcaseyouselecttheelementfromtheend,ratherthanthebeginning,ofthearray.Thismeansthefollowing− print$days[-1];#outputsSun print$days[-7];#outputsMon SequentialNumberArrays Perloffersashortcutforsequentialnumbersandletters.Ratherthantypingouteachelementwhencountingto100forexample,wecandosomethinglikeasfollows− LiveDemo #!/usr/bin/perl @var_10=(1..10); @var_20=(10..20); @var_abc=(a..z); print"@var_10\n";#Printsnumberfrom1to10 print"@var_20\n";#Printsnumberfrom10to20 print"@var_abc\n";#Printsnumberfromatoz Heredoubledot(..)iscalledrangeoperator.Thiswillproducethefollowingresult− 12345678910 1011121314151617181920 abcdefghijklmnopqrstuvwxyz ArraySize Thesizeofanarraycanbedeterminedusingthescalarcontextonthearray-thereturnedvaluewillbethenumberofelementsinthearray− @array=(1,2,3); print"Size:",scalar@array,"\n"; Thevaluereturnedwillalwaysbethephysicalsizeofthearray,notthenumberofvalidelements.Youcandemonstratethis,andthedifferencebetweenscalar@arrayand$#array,usingthisfragmentisasfollows− LiveDemo #!/usr/bin/perl @array=(1,2,3); $array[50]=4; $size=@array; $max_index=$#array; print"Size:$size\n"; print"MaxIndex:$max_index\n"; Thiswillproducethefollowingresult− Size:51 MaxIndex:50 Thereareonlyfourelementsinthearraythatcontainsinformation,butthearrayis51elementslong,withahighestindexof50. AddingandRemovingElementsinArray Perlprovidesanumberofusefulfunctionstoaddandremoveelementsinanarray.Youmayhaveaquestionwhatisafunction?Sofaryouhaveusedprintfunctiontoprintvariousvalues.Similarlytherearevariousotherfunctionsorsometimecalledsub-routines,whichcanbeusedforvariousotherfunctionalities. Sr.No. Types&Description 1 push@ARRAY,LIST Pushesthevaluesofthelistontotheendofthearray. 2 pop@ARRAY Popsoffandreturnsthelastvalueofthearray. 3 shift@ARRAY Shiftsthefirstvalueofthearrayoffandreturnsit,shorteningthearrayby1andmovingeverythingdown. 4 unshift@ARRAY,LIST Prependslisttothefrontofthearray,andreturnsthenumberofelementsinthenewarray. LiveDemo #!/usr/bin/perl #createasimplearray @coins=("Quarter","Dime","Nickel"); print"1.\@coins=@coins\n"; #addoneelementattheendofthearray push(@coins,"Penny"); print"2.\@coins=@coins\n"; #addoneelementatthebeginningofthearray unshift(@coins,"Dollar"); print"3.\@coins=@coins\n"; #removeoneelementfromthelastofthearray. pop(@coins); print"4.\@coins=@coins\n"; #removeoneelementfromthebeginningofthearray. shift(@coins); print"5.\@coins=@coins\n"; Thiswillproducethefollowingresult− 1.@coins=QuarterDimeNickel 2.@coins=QuarterDimeNickelPenny 3.@coins=DollarQuarterDimeNickelPenny 4.@coins=DollarQuarterDimeNickel 5.@coins=QuarterDimeNickel SlicingArrayElements Youcanalsoextracta"slice"fromanarray-thatis,youcanselectmorethanoneitemfromanarrayinordertoproduceanotherarray. LiveDemo #!/usr/bin/perl @days=qw/MonTueWedThuFriSatSun/; @weekdays=@days[3,4,5]; print"@weekdays\n"; Thiswillproducethefollowingresult− ThuFriSat Thespecificationforaslicemusthavealistofvalidindices,eitherpositiveornegative,eachseparatedbyacomma.Forspeed,youcanalsousethe..rangeoperator− LiveDemo #!/usr/bin/perl @days=qw/MonTueWedThuFriSatSun/; @weekdays=@days[3..5]; print"@weekdays\n"; Thiswillproducethefollowingresult− ThuFriSat ReplacingArrayElements Nowwearegoingtointroduceonemorefunctioncalledsplice(),whichhasthefollowingsyntax− splice@ARRAY,OFFSET[,LENGTH[,LIST]] Thisfunctionwillremovetheelementsof@ARRAYdesignatedbyOFFSETandLENGTH,andreplacesthemwithLIST,ifspecified.Finally,itreturnstheelementsremovedfromthearray.Followingistheexample− LiveDemo #!/usr/bin/perl @nums=(1..20); print"Before-@nums\n"; splice(@nums,5,5,21..25); print"After-@nums\n"; Thiswillproducethefollowingresult− Before-1234567891011121314151617181920 After-12345212223242511121314151617181920 Here,theactualreplacementbeginswiththe6thnumberafterthatfiveelementsarethenreplacedfrom6to10withthenumbers21,22,23,24and25. TransformStringstoArrays Let'slookintoonemorefunctioncalledsplit(),whichhasthefollowingsyntax− split[PATTERN[,EXPR[,LIMIT]]] Thisfunctionsplitsastringintoanarrayofstrings,andreturnsit.IfLIMITisspecified,splitsintoatmostthatnumberoffields.IfPATTERNisomitted,splitsonwhitespace.Followingistheexample− LiveDemo #!/usr/bin/perl #defineStrings $var_string="Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $var_names="Larry,David,Roger,Ken,Michael,Tom"; #transformabovestringsintoarrays. @string=split('-',$var_string); @names=split(',',$var_names); print"$string[3]\n";#ThiswillprintRoses print"$names[4]\n";#ThiswillprintMichael Thiswillproducethefollowingresult− Roses Michael TransformArraystoStrings Wecanusethejoin()functiontorejointhearrayelementsandformonelongscalarstring.Thisfunctionhasthefollowingsyntax− joinEXPR,LIST ThisfunctionjoinstheseparatestringsofLISTintoasinglestringwithfieldsseparatedbythevalueofEXPR,andreturnsthestring.Followingistheexample− LiveDemo #!/usr/bin/perl #defineStrings $var_string="Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $var_names="Larry,David,Roger,Ken,Michael,Tom"; #transformabovestringsintoarrays. @string=split('-',$var_string); @names=split(',',$var_names); $string1=join('-',@string); $string2=join(',',@names); print"$string1\n"; print"$string2\n"; Thiswillproducethefollowingresult− Rain-Drops-On-Roses-And-Whiskers-On-Kittens Larry,David,Roger,Ken,Michael,Tom SortingArrays Thesort()functionsortseachelementofanarrayaccordingtotheASCIINumericstandards.Thisfunctionhasthefollowingsyntax− sort[SUBROUTINE]LIST ThisfunctionsortstheLISTandreturnsthesortedarrayvalue.IfSUBROUTINEisspecifiedthenspecifiedlogicinsidetheSUBTROUTINEisappliedwhilesortingtheelements. LiveDemo #!/usr/bin/perl #defineanarray @foods=qw(pizzasteakchickenburgers); print"Before:@foods\n"; #sortthisarray @foods=sort(@foods); print"After:@foods\n"; Thiswillproducethefollowingresult− Before:pizzasteakchickenburgers After:burgerschickenpizzasteak PleasenotethatsortingisperformedbasedonASCIINumericvalueofthewords.Sothebestoptionistofirsttransformeveryelementofthearrayintolowercaselettersandthenperformthesortfunction. The$[SpecialVariable Sofaryouhaveseensimplevariablewedefinedinourprogramsandusedthemtostoreandprintscalarandarrayvalues.Perlprovidesnumerousspecialvariables,whichhavetheirpredefinedmeaning. Wehaveaspecialvariable,whichiswrittenas$[.Thisspecialvariableisascalarcontainingthefirstindexofallarrays.BecausePerlarrayshavezero-basedindexing,$[willalmostalwaysbe0.Butifyouset$[to1thenallyourarrayswilluseon-basedindexing.Itisrecommendednottouseanyotherindexingotherthanzero.However,let'stakeoneexampletoshowtheusageof$[variable− LiveDemo #!/usr/bin/perl #defineanarray @foods=qw(pizzasteakchickenburgers); print"Foods:@foods\n"; #Let'sresetfirstindexofallthearrays. $[=1; print"Foodat\@foods[1]:$foods[1]\n"; print"Foodat\@foods[2]:$foods[2]\n"; Thiswillproducethefollowingresult− Foods:pizzasteakchickenburgers Foodat@foods[1]:pizza Foodat@foods[2]:steak MergingArrays Becauseanarrayisjustacomma-separatedsequenceofvalues,youcancombinethemtogetherasshownbelow− LiveDemo #!/usr/bin/perl @numbers=(1,3,(4,5,6)); print"numbers=@numbers\n"; Thiswillproducethefollowingresult− numbers=13456 Theembeddedarraysjustbecomeapartofthemainarrayasshownbelow− LiveDemo #!/usr/bin/perl @odd=(1,3,5); @even=(2,4,6); @numbers=(@odd,@even); print"numbers=@numbers\n"; Thiswillproducethefollowingresult− numbers=135246 SelectingElementsfromLists Thelistnotationisidenticaltothatforarrays.Youcanextractanelementfromanarraybyappendingsquarebracketstothelistandgivingoneormoreindices− LiveDemo #!/usr/bin/perl $var=(5,4,3,2,1)[4]; print"valueofvar=$var\n" Thiswillproducethefollowingresult− valueofvar=1 Similarly,wecanextractslices,althoughwithouttherequirementforaleading@character− LiveDemo #!/usr/bin/perl @list=(5,4,3,2,1)[1..3]; print"Valueoflist=@list\n"; Thiswillproducethefollowingresult− Valueoflist=432 PreviousPage PrintPage NextPage Advertisements
延伸文章資訊
- 1Adding elements to an array in Perl - Stack Overflow
I have this code where I want to add 10, 11 and 12 to array arr. my ...
- 2Manipulating Perl arrays: shift, unshift, push, pop - Perl Maven
The push function can add one or more values to the end of an array. (Well, it can also add 0 val...
- 3Appending One Array to Another - Perl Cookbook [Book]
Appending One Array to Another Problem You want to join two arrays by appending all the elements ...
- 4Arrays - Learn Perl - Free Interactive Perl Tutorial
Perl array variables store an ordered list of scalar values. ... push(@array, element) : add elem...
- 5Perl - Arrays - Tutorialspoint
Adding and Removing Elements in Array. Perl provides a number of useful functions to add and remo...