PERL - Array Variables - Tizag Tutorials
文章推薦指數: 80 %
When adding elements using push() or shift() you must specify two arguments, first the array name and second the name of the element to add. Removing an element ...
PERL-ArrayVariables
Arraysareaspecialtypeofvariablethatstoreliststyledatatypes.Eachobjectofthelististermedanelementandelementscaneitherbeastring,anumber,oranytypeofscalardataincludinganothervariable.
AdvertiseonTizag.com
PlaceanarrayintoaPERLscript,usingtheatsymbol(@).
perlarrays.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n"; #HTTPHEADER
#DEFINEANARRAY
@coins=("Quarter","Dime","Nickel");
#PRINTTHEARRAY
print"@coins";
print"
";
print@coins;
Checkthesyntaxhere.Weprintedthesamearraytwiceusingquotesaroundthefirstline.Noticehowthelinewithquotesarounditprintsnicelytothebrowserleavingspacesbetweeneachword.PERLdoesthisautomaticallyasitassumesthequotationsaremeantforastringandstringsareusuallycomprisedofwordsthatrequirespacingbetweeneachword.
PERL-ArrayIndexing
Eachelementofthearraycanbeindexedusingascalarversionofthesamearray.Whenanarrayisdefined,PERLautomaticallynumberseachelementinthearraybeginningwithzero.Thisphenomenonistermedarrayindexing.
arrayindexing.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n"; #HTTPHEADER
#DEFINEANARRAY
@coins=("Quarter","Dime","Nickel");
#PRINTTHEWHOLEARRAY
print"@coins";
#PRINTEACHSCALARELEMENT
print"
";
print$coins[0];#Printsthefirstelement
print"
";
print$coins[1];#Printsthe2ndelement
print"
";
print$coins[2];#Printsthe3rdelement
arrayindexing.pl:
QuarterDimeNickel
Quarter
Dime
Nickel
Elementscanalsobeindexedbackwardsusingnegativeintegersinsteadofpositivenumbers.
arrayindexing2.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n"; #HTTPHEADER
#DEFINEANARRAY
@coins=("Quarter","Dime","Nickel");
#PRINTTHEWHOLEARRAY
print"@coins";
#PRINTEACHSCALARELEMENT
print"
";
print$coins[0];#Printsthefirstelement
print"
";
print$coins[-1];#Printsthelastelement
print"
";
print$coins[-2];#Prints2ndtolastelement
arrayindexing2.pl:
QuarterDimeNickel
Quarter
Nickel
Dime
PERL-TheqwSubroutine
Quotationscanbeahassle,especiallyifthearrayyouwishtobuildhasmorethan5elements.Usethisneatlittlesubroutinetoremovetheneedforquotesaroundeachelementwhenyoudefineanarray.
PERLCode:
#!/usr/bin/perl
print"content-type:text/html\n\n"; #HTTPHEADER
#DEFINEANARRAYWITHOUTQUOTES
@coins=qw(QuarterDimeNickel);
print"@coins";
Display:
QuarterDimeNickel
PERL-SequentialNumberArrays
PERLoffersashortcutforsequentialnumbersandletters.Ratherthantypingouteachelementwhencountingto100forexample,wecandosomethinglikethis:
sequentialarrays.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n"; #HTTPHEADER
#SHORTCUTSSAVETIME
@10=(1..10);
@100=(1..100);
@1000=(100..1000);
@abc=(a..z);
#PRINT'EMTOTHEBROWSER
print"@10
";
print"@100
";
print"@1000
";
print"@abc
";
PERL-FindingthelengthofanArray
Retrievinganumericalvaluethatrepresentsthelengthofanarrayisatwostepprocess.First,youneedtosetthearraytoascalarvariable,thenjustprintthenewvariabletothebrowserasshownbelow.
Therearetwowaystosetanarraytoscalarmode.Wecanusethescalar()functionorwecanredefinethearrayasascalarvariable.
findlength.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n"; #HTTPHEADER
@nums=(1..20);
@alpha=("a".."z");
#SCALARFUNCTION
printscalar(@nums)."
";
printscalar(@alpha)."
";
#REDEFINETOSCALAR
$nums=@nums;
$alpha=@alpha;
print"$nums
";
print"$alpha
";
print"Thereare$numsnumericalelements
";
print"Thereare".scalar(@alpha)."lettersinthealphabet!";
findlength.pl:
20
26
20
26
Thereare20numericalelements
Thereare26lettersinthealphabet!
Settingourarraytoascalardatatypetransformedourarrayintoscalardata.AsaresultPERLisforcedtocountthrougheachelementandreturnavaluerepresentingthearray.
PERL-AddingandRemovingElements
Addingelementsisabreeze,weusethefollowingfunctionstoadd/removeandelements:
push()-addsanelementtotheendofanarray.
unshift()-addsanelementtothebeginningofanarray.
pop()-removesthelastelementofanarray.
shift()-removesthefirstelementofanarray.
Whenaddingelementsusingpush()orshift()youmustspecifytwoarguments,firstthearraynameandsecondthenameoftheelementtoadd.Removinganelementwithpop()orshift()onlyrequiresthatyousendthearrayasanargument.
modifyarrays.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
#ANARRAY
@coins=("Quarter","Dime","Nickel");
#ADDELEMENTS
push(@coins,"Penny");
print"@coins";
print"
";
unshift(@coins,"Dollar");
print"@coins";
#REMOVEELEMENTS
pop(@coins);
print"
";
print"@coins";
shift(@coins);
print"
";
#BACKTOHOWITWAS
print"@coins";
modifyarrays.pl:
QuarterDimeNickelOuroriginalArray,3elements.
QuarterDimeNickelPennyAddpennytotheend.
DollarQuarterDimeNickelPennyAddDollartothebeginning.
DollarQuarterDimeNickelRemovePenny.
QuarterDimeNickelRemovedollar,backtotheoriginal!
ArrayFunctions:
FunctionDefinition
push(@array,Element)Addstotheendofanarray
pop(@array)Removesthelastelementofthearray
unshift(@array,Element)Addstothebeginningofanarray
shift(@array)Removesthefirstelementofanarray
delete$array[index]Removesanelementbyindexnumber
Itisalsopossibletoremoveanyelementbyitsindexednumber.Justremembertousethescalarformofthearraywhendoingso.($)
PERL-SlicingArrayElements
Thereisnospecificslice()functionforslicingupelementsofanarray.InsteadPERLallowsustocreateanewarraywithelementsofanotherarrayusingarrayindexing.
slicendice.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
@coins=qw(QuarterDimeNickelPenny);
@slicecoins=@coins[0,2];
print"@slicecoins\n";
print"
";
Whenhandlinglistsofsequentialnumbers,therangeoperatorcanquicklybecomeyourfavoritetoolforslicinguparrays.
myrangefriend.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
#SEQUENTIALARRAY
@nums=(1..200);
@slicenums=@nums[10..20,50..60,190..200];
print"@slicenums";
myrangefriend.pl:
111213141516171819202151525354555657
58596061191192193194195196197198199200
PERL-ReplacingArrayElements
Replacingelementsispossiblewiththesplice()function.Splice()requiresahandfulofargumentsandtheformulareads:splice(@array,first-element,sequential_length,nameofnewelements).
Essentially,yousendPERLanarraytosplice,thendirectittothestartingelement,countthroughhowmanyelementstoreplace,andthenfillinthemissingelementswithnewinformation.
replacewithsplice.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHeader
@nums=(1..20);
splice(@nums,5,5,21..25);
print"@nums";
Takenoteofthefactthattheactualreplacementbeginsafterthe5thelement,startingwiththenumber6intheexampleabove.Fiveelementsarethenreplacedfrom6-10withthenumbers21-25.Letthe"Ooohing"and"Ahhhing"begin."
PERL-TransformStringstoArrays
Withthesplitfunction,itispossibletotransformastringintoanarray.Todothissimplydefineanarrayandsetitequaltoasplitfunction.Thesplitfunctionrequirestwoarguments,firstthecharacterofwhichtosplitandalsothestringvariable.
stringtoarray.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
#DEFINEDSTRINGS
$astring="Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$namelist="Larry,David,Roger,Ken,Michael,Tom";
#STRINGSARENOWARRAYS
@array=split('-',$astring);
@names=split(',',$namelist);
#PRINTTHENEWARRAYS
print@array."
";
print"@names";
split.pl:
RainDropsOnRosesAndWhiskersOnKittens
LarryDavidRogerKenMichaelTom
Noticeyouhavetosendthesplitfunctionwherethesplitwilloccur.Inthefirstexample,thesplitwascalledateachhyphen.Inthelatterexamplethenamesweresplitbyacomma,allowingforthesplittotakeplacebetweeneachname.
Likewise,wecanusethejoin()functiontorejointhearrayelementsandformonelong,scalarstring.
arraytostring.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
#ACOUPLEOFARRAYS
@array=("David","Larry","Roger","Ken","Michael","Tom");
@array2=qw(PizzaSteakChickenBurgers);
#JOIN'EMTOGETHER
$firststring=join(",",@array);
$secondstring=join("",@array2);
#PRINTTHESTRINGS
print"$firststring
";
print"$secondstring";
join.pl:
David,Larry,Roger,Ken,Michael,Tom
PizzaSteakChickenBurgers
Thecharactersspecifiedinourjoin()argumentarethecharactersusedinbetweeneachelementofthearray.Thisallowsustoformatthenewstringswithblankspacesbetweeneachword.WecouldreplacetheblankspaceswithanycharactersincludingHTMLElementssuchasalinebreaktag.
stringformatting.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
@array2=qw(PizzaSteakChickenBurgers);
$string=join("
",@array2);
print"$string";
stringformatting.pl:
Pizza
Steak
Chicken
Burgers
PERL-SortingArrays
Thesort()functionsortseachelementofanarrayaccordingtoASCIINumericstandards.PleaseviewASCII-TableforacompletelistingofeveryASCIINumericcharacter.
Becausethesort()reliesonASCIINumericvalues,problemscanarisewithsortingcapitallettersandlowercaseletters.Let'swalkthroughanexampleofexactlywhatcanhappen.
sortarrays.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
#TWOARRAYS
@foods=qw(pizzasteakchickenburgers);
@Foods=qw(PizzaSteakchickenburgers);
#SORT'EM
@foods=sort(@foods);
@Foods=sort(@Foods);
#PRINTTHENEWARRAYS
print"@foods
";
print"@Foods";
Display:
burgerschickenpizzasteakPizzaSteakburgerschicken
Sowhathappened?Weperformedthesamefunctionontwonearlyidenticalarraysandachievedcompletedifferentresults.CapitallettershavealowerASCIINumericvaluethanlowercaseletters.Thefactthatoursecondarrayhasamixofcapitalsandlowercasethrowsoursortingoutofwhack.Perhapsthebestoptionistofirsttransformeveryelementofthearrayintolowercaselettersandthenperformthesortfunction.
sortarrays.pl:
#!/usr/bin/perl
print"content-type:text/html\n\n";#HTTPHEADER
@Foods=qw(PizzaSteakchickenburgers);
#TRANSFORMTOLOWERCASE
foreach$food(@Foods){
push(@foods,"\L$food");
}
#SORT
@foods=sort(@foods);
#PRINTTHENEWARRAY
print"@foods";
Display:
burgerschickenpizzasteak
Thisexampledivesoffthedeepend,beingthatweintroducedaforeachloop.Don'tbeafraidoftheloop,justunderstandthatconceptthatideally,elementsneedtobeconvertedbeforesortingusingthesort()function.
GoBackContinueFoundSomethingWronginthisLesson?ReportaBugorCommentonThisLesson-YourinputiswhatkeepsTizagimprovingwithtime!
WebReference
HelpTizagGrow
AdvertiseHere
MoreTutorials!
2003-2008ErackNetwork|Copyright|PrivacyPolicy|AdvertisingInformation
SitedesignbySeattleWebDesign
延伸文章資訊
- 1Arrays - Learn Perl - Free Interactive Perl Tutorial
Perl array variables store an ordered list of scalar values. ... push(@array, element) : add elem...
- 2How 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 ...
- 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 ...
- 4Using the Perl push() function
You can use the push function to add new elements to the end of an array. Example 1. Adding an it...
- 5Perl | Arrays (push, pop, shift, unshift) - GeeksforGeeks
Perl provides various inbuilt functions to add and remove the elements in an array. ... This func...