Array push and references - perl - Stack Overflow
文章推薦指數: 80 %
A reference to that array is created and stored in the ... /usr/bin/perl use Data::Dumper; my @Numbers=(); push(@Numbers,[3,8,9]); ... 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 Arraypushandreferences AskQuestion Asked 1year,5monthsago Modified 1year,3monthsago Viewed 242times 3 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. IamabeginnerperlprogrammerandI'vecomeacrossapieceofcodewhichlooksasfollows: my@Numbers=(); push(@{$Numbers[0]},3,8,9); push(@{$Numbers[1]},5); printjoin(",",@{$Numbers[0]}); print"\n"; printjoin(",",@{$Numbers[1]}); print"\n"; I'mhavingdifficultyinunderstandingwhatthepushonto@{$Numbers[0]}and@{$Numbers[1]}isdoing.Doesthepushautomaticallycreatearrayreferencesto[3,8,9]and[5]intheNumbersarray?Ihavenodifficultyinunderstandingthesyntaxbelow,whichisfarmorecommonIsuppose,butIhaven'tcomeacrossthesyntaxthatI'vepastedabove,whichIguessalsousesauto-vivificationtopopulatetheNumbersarraywithreferences. my@Numbers=(); push(@Numbers,[3,8,9]); push(@Numbers,[5]); printjoin(",",@{$Numbers[0]}); print"\n"; printjoin(",",@{$Numbers[1]}); print"\n"; perl Share Improvethisquestion Follow editedJul17,2021at3:49 sdp askedMay12,2021at6:51 sdpsdp 9711silverbadge44bronzebadges 4 Printarrayorhashdumpertounderstandthestructure.SeeData::Dumper. – vkk05 May12,2021at7:00 @vkk05UsedData::Dumpertoprintthearray.Itlookslikethefirstandsecondexamplesareexactlythesame.BothcreatetworeferencesintheNumbersarray.Itjustthatthefirstexampleandsyntaxisuncommon-atleastIhaven'tseenitanywhere. – sdp May12,2021at7:07 1 Thefirstcasemakessenseifyouuse@NumberslikeanordereddictionarywheretheKeyisnumeric.Youcanthenlaterpush@{$Numbers[$NumericKey]},@AdditionalNumbers;(notethatit'svalidtohave"gaps"intheindexsequence) – TedLyngmo May12,2021at7:14 perldoc.perl.org/perllol#Access-and-Printing – mpapec May12,2021at7:39 Addacomment | 2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 3 Therearetwofeaturesatplay,andoneisindeedautovivification. I'llgointoautovivificationinasecond.First,let'sconsiderthefactthat@Numbersisemptywhenweaccess$Numbers[0].Thisisnotaproblem.Perlwillautomaticallyextendthearraytoincludethiselement.[1] my@a; $a[3]=123;#ok! print(Dumper(\@a));#[undef,undef,undef,123] Thisisn'twhatthedocumentationcallsautovivification,butit'ssimilarenoughthatsomepeoplewillcallitautovivificationtoo. AsImentioned,thesecondfeatureisindeedautovivification.Autovivificationistheautomaticcreationofananonymousvariablethroughdereferencing.Specifically,ithappenswhendereferencinganundefinedscalar.[2] Inthiscase,autovivificationcreatesanarraysince@BLOCKisanarraydereference.Areferencetothatarrayiscreatedandstoredinthepreviously-undefscalar. Inotherwords,autovivificationmakes push@{$ref},LIST; effectivelyequivalentto push@{$ref//=[]},LIST; or if(!defined($ref)){ my@anon; $ref=\@anon; } push@$ref,LIST; Itwasprobablyjustacontrivedexampleforthequestion,butnotethatthepostedcodeisweird.Weknow$Numbers[0]and$Numbers[1]areundef,sowedon'tneedpush. my@nums; @{$nums[0]}=(3,8,9);#Alsoautovivification. @{$nums[1]}=5; Andsinceweknow$Numbers[0]and$Numbers[1]areundef,wethere'snopointinrelyingonautovivificationeither. my@nums; $nums[0]=[3,8,9]; $nums[1]=[5]; Let'sgetridofthosehardcodedindexes. my@nums; push@nums,[3,8,9]; push@nums,[5]; Andafinalsimplification. my@nums=( [3,8,9], [5], ); Thisonlyhappensinanlvaluecontext,meaningwhenthereferencedvariableisexpectedtobemodified/modifiable.say$a[@a];won'textendthearrayeventhoughitaccessesanelementafteritslastelement. Italsohastobeinanlvaluecontext.my@copy=@{$undef};willnotautovivify. Share Improvethisanswer Follow editedMay12,2021at15:49 answeredMay12,2021at9:13 ikegamiikegami 352k1515goldbadges254254silverbadges499499bronzebadges 1 1 Youmademesay"autovivification"11times.Makethat12. – ikegami May12,2021at9:53 Addacomment | 1 UseData::Dumpertoseewhatishappening. #!/usr/bin/perl useData::Dumper; my@Numbers=(); push(@Numbers,[3,8,9]); push(@Numbers,[5]); printDumper(@Numbers); Output: $VAR1=[ 3, 8, 9 ]; $VAR2=[ 5 ]; IfyoupassanarraytoDumper,theelementsareinterpretedasmultiplearguments. Roundparenthesisarearraysandrectangularparenthesisarearrayreferences.pushworksonlyonarraysbutnotonarrayreferences.SeethePerlmanualperlreffordetailsaboutreferencingandde-referencing. Youcanconvertanarraytoanarrayreferencewithabackslash: printDumper(\@Numbers); NowDumpershowsthereferencewithrectangularparenthesis. $VAR1=[ [ 3, 8, 9 ], [ 5 ] ]; YoucanalsomakeNumbersareference,butthenyouhavetode-referenceitbeforeyoupassittopush. #!/usr/bin/perl useData::Dumper; my$Numbers=[]; push(@$Numbers,[3,8,9]); push(@$Numbers,[5]); printDumper($Numbers); Nowyouwillunderstandthis: push(@{$Numbers[0]},3,8,9); $Numbers[0]takesthefirstelementofanarray(whichisascalar). @{$Numbers[0]}de-referencesthescalarintoanarray. pushappendsthethreescalars3,8and9tothede-referencedarray. Thisresultsintoacreationofanarrayreference. Share Improvethisanswer Follow editedMay12,2021at9:31 ikegami 352k1515goldbadges254254silverbadges499499bronzebadges answeredMay12,2021at8:03 cevingceving 20.5k1111goldbadges9595silverbadges164164bronzebadges 15 1 Tip:Nopointemptyinganemptyarray.my@Numbers=();simplifiestomy@Numbers; – ikegami May12,2021at8:12 1 Re"Roundparenthesisarearrays",Completelyfalse.()hasNOTHINGtodowitharrays.Parensmerelychangeprecedenceliketheydoinmath.Forexample,my@a=4;,my@a=4..5;,etcWeonlyusetheminmy@a=(4,5);causeitwouldmean(my@a=4),5;otherwise.my@a;isthenamedequivalentof[],not(). – ikegami May12,2021at8:22 1 yes,anundefinedscalarisascalar.Arrayandhashvaluesarescalars. – ikegami May12,2021at8:26 1 @sdp,Yes.push@{$Numbers[0]},3,8,9;iseffectivelyshortforpush@{$Numbers[0]//=[]},3,8,9;,whichwecallautovivification.There'sastepmissingintheexplanationatthebottom,whereanarrayisautomaticallycreatedwhenanundefinedscalarisusedasareference. – ikegami May12,2021at8:48 2 Iwasn'tgoingtobecauseIthoughtthisanswerwasdoingagoodjobofexplainingwhatthecodedoes.Butthatwasn'ttheOP'squestion.Theyarespecificallyaskingaboutautovivifcation,andyouseemtobestrugglingwiththat.Ihavejustpostedananswer. – ikegami May12,2021at9:15 | Show10morecomments 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?Browseotherquestionstaggedperloraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Related 2 HowcanIprintNarrayelementswithdelimitersperline? 1 PullspecificinformationfromalonglistwithPerl 0 parsingjsoninperl 5 Perl:Beginner.WhichdatastructureshouldIuse? 1 Perl:increment2darraycell? 3 Perlexpressionusingacombinationofhashandarray 0 Perl-returningtwoarrayreferencesfromasubroutine,wishtoprocessonlythefirst 1 CountingdictionaryelementsfromPerltoPython 3 NotaHASHreferenceerrorreceivedwhiletryingtoloopthrougharrayinsideahash 0 Perl:ArrayofArrayReferences HotNetworkQuestions AlphabetChecksum AncientNotableSchoarsthosewhostudiedmusic-weretheysinnersaccordingtoIslam? Howdovintagesteelframescomparetomodernones? Wouldlanguagehavemeaningiftherewasnoconsciousness? Howisitpossibletofiltereitherhighorlowfrequenciesofasinglesinewave? WhyisthePassivevoiceof"einladen"usedwith"sein"andnotwerden? CanIpublishmythesisonlineandgetpaid? HowdoesTrainingworkwithWarriorSpirit? Misuseofmixedeffectsmodel Isthereawaytosetupashortcutto"re-run"theDelphiLSPinstances? HowcanIprintoutthefirstlineofallthefilesthatmatchcertain"find"criteria? Howtoobtainaminor'spassportwithanabsentparent IsGoogleStreetViewcoverageinGermanyexpectedtoincrease? Smpswithswitchingstageaftertransformer DoRSAsignaturesreallyneedpadding? UnderwhatauthoritycantheUSmakefederalreservenoteslegaltender? WhereisthisparkinMontreal,withautumncolortreesandpond? WhoorwhatcreatedtheT'au? Bootablefloppydisk HowcanIconnectTikZnodeswithmultiple-cornerlines? WhydoesMOS6502requireanexternalclockifithasaninternaloscillator? WhyareUKprimeministersresigning,ratherthanwaitingouttheirtermandenjoyingthebenefits? HowdoyoudescribesomeoneasashapeshifterinLatin? DoGFI/GFCIoutletshaveapotentialtodamageNespressomachines(andcoffeemachines?) morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Perl | Arrays (push, pop, shift, unshift) - GeeksforGeeks
Perl provides various inbuilt functions to add and remove the elements in an array. ... This func...
- 2push - Perldoc Browser
Returns the number of elements in the array following the completed push . Starting with Perl 5.1...
- 3Perl push()函數 - 極客書
#!/usr/bin/perl -w #by www.gitbook.net $, = ","; @array = ( 1, 2 ); print "Before pusing elements...
- 4Perl | push() Function - GeeksforGeeks
push() function in Perl is used to push a list of values onto the end of the array. push() functi...
- 5Perl push()用法及代碼示例- 純淨天空
Perl中的push()函數用於將值列表推送到數組的末尾。 push()函數通常與pop結合使用以 ... Calling push function to # add a list of el...