Arrays - Learn Perl - Free Interactive Perl Tutorial
文章推薦指數: 80 %
Perl array variables store an ordered list of scalar values. ... push(@array, element) : add element or elements into the end of the array ... learn-perl.org Home(current) About Certify MoreLanguages Python Java HTML Go C C++ JavaScript PHP Shell C# Perl Ruby Scala SQL English Star Fork Python Java HTML Go C C++ JavaScript PHP Shell C# Perl Ruby Scala SQL Arrays Arrays Perlarrayvariablesstoreanorderedlistofscalarvalues.Thearrayvariablenamebeginswiththe@symbol.Torefertoasingleelementofanarray,thevariablenamemuststartwitha$followedbytheindexoftheelementinsquarebrackets([]).Theindexofthefirstarrayelementis0. Forexample: #Multipleelementsvalueassignment,whichcreatesanarraywithfourelements,somenumericandsomestring. @array=(25,"John","Mary",-45.34); print"$array[1]\n";#John #Directassignmentofanelementwithaspecificindex. $array[5]="Tom"; Accessingarrayelementscanbedonewithanegativeindex.Thiswillselectelementsfromtheendofthearray. #Usetheqw//operatorwhichreturns #anarrayofstringelementsmadeoftheoriginalstringdelimitedbywhitespace. @array_from_text=qw/Perlisagreatscriptinglanguage/; print"$array_from_text[0]\n";#Perl print"$array_from_text[1]\n";#is print"$array_from_text[-3]\n";#great Perlsupportsashortcutforsequentiallettersornumbers.Usetherangeoperator..toassignsequentialvaluestoarrayelements.Forexample: @month_numbers=(0..12);#0123456789101112 print"numberofmonth2is$month_numbers[2]\n";#2 Thesizeorlengthofthearraycanbeevaluatedbythescalarcontextofthearrayorbyusingthescalarvariablevalueofthelastarrayelement.Thescalarcontextisreferedtobyscalar@array.Thelastarrayelementisreferedtoby$#array.If@arrayisempty,thevalueof$#arrayis-1. @month_numbers=(0..12);#0123456789101112 print"Size:",scalar@month_numbers,"\n"; print"Indexoflastarrayelement:",$#month_numbers,"\n"; @empty=(); print"Lastelementof@empty:$#array";#-1 Perloffersmanyusefulfunctionstomanipulatearraysandtheirelements: push(@array,element):addelementorelementsintotheendofthearray $popped=pop(@array):deleteandreturnthelastelementofthearray $shifted=shift(@array):deleteandreturnthefirstelementofthearray unshift(@array):addelementorelementsintothebeginningofthearray Examples: #1.defineinitialarraycontents @basket=("Apple","Banana","Carrot"); print"1.My\@basketarrayis:@basket\n"; #2.addelementattheendofthearray push(@basket,"Orange"); print"2.My\@basketarrayis:@basket\n"; #3.addelementatthebeginningofthearray unshift(@basket,"Avocado"); print"3.My\@basketarrayis:@basket\n"; #4.removeelementfromtheendofthearray pop(@basket); print"4.My\@basketarrayis:@basket\n"; #5.removeelementfromthebeginningofthearray shift(@basket); print"5.My\@basketarrayis:@basket\n"; Slicinganarrayisselectingmorethanoneelementfromanarraytocreateanotherarray.Thespecificationofaslicemustbealistofcomma-delimitedvalidindexnumbers,orusingtherangeoperator. Examples: @Months=qw/JanFebMarAprMayJunJulAugSepOctNovDec/; @winter_canada=@Months[-1,0,1]; @winter_brazil=@Months[5..7]; print"wintermonthsinCanadaare:@winter_canada\n";#DecJanFeb print"wintermonthsinBrazilare:@winter_brazil\n";#JunJulAug Youcanusethesplit()functiontosplitalongstringintoseparatearrayelements,usingavalueasadelimiterstring. $Months='Jan,Feb,Mar,apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'; @array_of_month_names=split(',',$Months); print"$Months\n"; print"@array_of_month_names\n"; Youcanusethejoin()functiontorejoinelementsofanarrayintoalongscalarstring,withanoptionaldelimiter. $Months='Jan,Feb,Mar,apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'; @array_of_month_names=split(',',$Months); $dash_delimited_monthlist=join('-',@array_of_month_names); $very_long_message=join('isfollowedby',@array_of_month_names); print"$Months\n"; print"@array_of_month_names\n"; print"$dash_delimited_monthlist\n"; print"$very_long_message\n"; Sinceasanarrayisacomma-delimitedlistofvaluesyoucaneasilycombinetwoarrayswiththemerge()function.Forexample: @group1=('John','Steve','Mary'); @group2=('Bill','Barack'); @combined_group=(@group1,@group2,'Jeff','Tom'); print"@combined_group\n"; Exercise Anarrayholdsalistofcellularphonemodels.AsecondarrayholdsthepriceofeachmodelinUSDollars.CreateathirdarraywhichcontainsthepriceofeachmodelinPoundsSterling.Assume1poundequals2USDollars.Astheresultprintonelinepermodelstatingitscostinpounds. Forexample:"OneiPhoneXcosts120pounds." StartExercise Sponsors Chapters Hello,World! VariablesandTypes ConditionalDecisions Loops Operators References Subroutines RegularExpressions ContributingTutorials Copyright©learn-perl.org.ReadourTermsofUseandPrivacyPolicy
延伸文章資訊
- 1Arrays - Learn Perl - Free Interactive Perl Tutorial
Perl array variables store an ordered list of scalar values. ... push(@array, element) : add elem...
- 2Perl | Arrays (push, pop, shift, unshift) - GeeksforGeeks
Perl provides various inbuilt functions to add and remove the elements in an array. ... This func...
- 3How do I append an element to a perl array? - Dave's Brain
Date: 2014nov11 Language: perl Q. How do I append an element to a perl array? A. Use push() like ...
- 4PERL - Array Variables - Tizag Tutorials
When adding elements using push() or shift() you must specify two arguments, first the array name...
- 5Perl - Arrays - Tutorialspoint
Adding and Removing Elements in Array. Perl provides a number of useful functions to add and remo...