Adding elements to an array in Perl - Stack Overflow

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

I have this code where I want to add 10, 11 and 12 to array arr. my ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam StackOverflowforTeamsismovingtoitsowndomain!Whenthemigrationiscomplete,youwillaccessyourTeamsatstackoverflowteams.com,andtheywillnolongerappearintheleftsidebaronstackoverflow.com. Checkyouremailforupdates. Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams AddingelementstoanarrayinPerl AskQuestion Asked 6years,9monthsago Modified 6years,9monthsago Viewed 23ktimes 1 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. IhavethiscodewhereIwanttoadd10,11and12toarrayarr. my@num=(0,1,2); my$i=10; formy$d(@num){ if(defined($d)){ my@arr; $arr[$d]=$i; $i=$i+1; my$dvv=dump(\@arr); print"****$dvv\n"; } } Theoutputis: ****[10] ****[undef,11] ****[undef,undef,12] Whyisonlythelastelementofarraydefined? arraysperl Share Improvethisquestion Follow editedJan20,2016at4:17 Scra askedJan20,2016at4:12 ScraScra 7911goldbadge11silverbadge88bronzebadges 1 Itisalwaysgoodtomaintainusestrictandusewarnings – Shantesh Jan20,2016at6:59 Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 12 AntonH'sansweraddressesthespecificproblemwithyourspecificcode,butthereareactuallywaystorewriteyourcodethatwouldavoidtheproblementirely.Amore"Perlish"waytoaccomplishthesamethingwouldbe: my@arr; formy$i(0..2){ push(@arr,$i+10); } Or: my@arr=map{$_+10}0..2; Orjust: my@arr=10..12; Share Improvethisanswer Follow editedMay23,2017at12:15 CommunityBot 111silverbadge answeredJan20,2016at5:42 MattJacobMattJacob 6,40822goldbadges2323silverbadges2727bronzebadges Addacomment  |  6 Sinceyouhavethedeclarationofthearraywithintheloop,itwillre-createiteachtime,removinganyvaluesthatwouldhavebeenplacedinitonpreviousiterationsoftheloop. Youshoulddeclaure@arrbeforetheloopifyouwantthevaluestostay: my@arr; formy$d(@num){ ... } Andbecauseofthisline: $arr[$d]; $disthepositiondefinedbytheotherarray(0,then1,then2).Soitputsthevalueof$iinthatpositioninthearray,andputsvaluesbeforetoundef. Share Improvethisanswer Follow editedJan20,2016at7:13 answeredJan20,2016at4:19 AntonHAntonH 6,35922goldbadges3131silverbadges4040bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedarraysperloraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Visitchat Linked 0 UnablestorealltheoutputstoarrayinPerl Related 2312 What'sthesimplestwaytoprintaJavaarray? 1431 DeletingarrayelementsinJavaScript-deletevssplice 3828 Sortarrayofobjectsbystringpropertyvalue 1832 HowtomergetwoarraysinJavaScriptandde-duplicateitems 2513 GetalluniquevaluesinaJavaScriptarray(removeduplicates) 1840 Getthelastiteminanarray 1983 Howtocreateanarraycontaining1...N 11048 HowcanIremoveaspecificitemfromanarray? 2124 HowcanIaddnewarrayelementsatthebeginningofanarrayinJavaScript? 5465 For-eachoveranarrayinJavaScript HotNetworkQuestions WorkplaceSafetyPolicyMakesMeLessSafe Boxblurthestring Smpswithswitchingstageaftertransformer Isthereamore"physicallymature"waytothinkabouttherighthandrulewithelectromagnetism? HowcanIkeeptheexistingguideswhentheunderlyingfileisupdatedinPhotoshop? Howdopropellanttransfertechnologieswork? Havefundamentalparticlesbeenobserved? Isthereawayasocietycouldproducetanksascheaplyascars? WhyareUKprimeministersresigning,ratherthanwaitingouttheirtermandenjoyingthebenefits? QGISdelimitedtextlayerisnotvisible Wouldlanguagehavemeaningiftherewasnoconsciousness? Mylibrarymembershipnumber Whatisthemostefficientwaytoget110Vfrom220Vsingle-phasewiring? Ifform8606isnotrequiredtosubmitforjustRothIRAcontributions?HowdoesIRSenforcethelimit? WhatisaScrumMastertodowhenmanagementdonotsupportAgileandScrum? Minimumrotationtogetthemaximumvalue Whatwouldan"excessivelysober"dwarflooklikeiftheyneedalcoholtofunction? Howtoobtainaminor'spassportwithanabsentparent Isthetermשָׁלֹום(peace)inIsaiah53:5usuallymisunderstood? HowdoProtestantsReceiveforgivenessforpost-BaptismalSins? TeXpointcommand EquilibriumconstantvsReactionrateconstant HowtoinstallLunarVimonWindows? Makegraduatedsymbolvaluesexceedwhatexistsinthedata morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?