What does assigning 'shift' to a variable mean? - Stack Overflow

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

shift uses the @_ variable which contains the values passed to a function or shift uses ... 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 Whatdoesassigning'shift'toavariablemean? AskQuestion Asked 11years,2monthsago Modified 4years,9monthsago Viewed 58ktimes 26 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. Example: usestrict; my$file=shift; open(IN,$file)||die"Unabletoopen$file\n"; open(OUT,">$file.$$")ordie$!; Whatisgoingonwiththemy$file=shift? perlvariables Share Improvethisquestion Follow editedJan12,2018at15:58 PeterMortensen 30.6k2121goldbadges102102silverbadges124124bronzebadges askedAug16,2011at18:03 seancurranseancurran 26911goldbadge33silverbadges33bronzebadges 3 thisisacommonPerlidiom,pleasereadperldocperlintroforcommonuseofPerl. – JoelBerger Aug17,2011at14:18 Istheproblemthatyoudon'tknowthedifferencebetween"shift"andshift()? – tchrist Aug18,2011at2:20 ExactduplicateofWhatdoesshift()doinPerl?. – PeterMortensen Jan12,2018at15:59 Addacomment  |  4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 32 Ifusedinthemainprogram,itwillshift(removeandreturn)thefirstvaluefrom@ARGV,theargumentlistofyourprogram.Ifusedinsideasubroutine,itwillshiftthefirstvaluefrom@_,theargumentlistofthesub.Seethedocumentationformoreinfo. Share Improvethisanswer Follow answeredAug16,2011at18:09 TLPTLP 65.8k99goldbadges8888silverbadges147147bronzebadges 5 Forlocaldocumentationofbuilt-infunctions:perldoc-fshift(Ubuntu,atleast,willneedyoutoinstalltheperl-docpackageforthistowork,buttellsyousowhenyoutryit). – ijw Aug17,2011at11:33 1 Forgivemebutthisseemsliketheworstconventioneverforcodereadability. – MrBrightside May31,2014at0:22 1 @CynicalOptimistItisonlyconfusingthefirsttimeyouseeit,unlessyouhavearatherbadmemoryfordetails. – TLP May31,2014at12:46 1 Irespectyou'reopinion,butIhavetodisagreefortheguywho'sreadingit.Fortheguywritingit,probablynotterrible... – MrBrightside May31,2014at17:04 1 @CynicalOptimistIthinkpeopleoftenareunfairwhenitcomestoPerl.Therearepreciousfewlanguagesthatyoucanunderstandcompletelywithoutconsultingamanual,whywouldPerlbeanydifferent?Idon'tunderstandwhypeoplethinkthat. – TLP Jun1,2014at15:34 Addacomment  |  16 Youcanreadthedocumentationonshift.Itisveryclear.shiftacceptsanarrayandextractsthefirstelement(actuallyremovingitfromthearray).Ifyoudon'tprovideanyarray,ituses@ARGV(theargumentstothecommandlineoftheprogram)toreadthedata.Ifyou'reinsideafunction,ituses@_,namely,theparametersofthefunction. Example: my@array=(1,2,3); my$value=shift@array; print$value;#willprint'1' Share Improvethisanswer Follow editedAug16,2011at18:12 answeredAug16,2011at18:07 DiegoSevillaDiegoSevilla 28.1k33goldbadges5656silverbadges8686bronzebadges 0 Addacomment  |  5 shiftusesthe@_variablewhichcontainsthevaluespassedtoafunctionorshiftuses@ARGVforthevaluespassedtothescriptitselfifshiftisreferencedoutsideofafunction. ONEWORDOFCAUTION:Itisprobablywise,especiallyinWindowswheremanypathscontainspaces,toputthefilenameandpathinsinglequoteswhenyoupassittothescriptorfunction.ThiswilltellPerlthatyouarepassingitasinglescalarvalueratherthananarrayofvalues.Youcanusedoublequotesifyouwanttointerpolatepartofthename.Forexample: my$path='C:\GoatKids'; func("$path\\goat.txt"); Or,fromthecommandlineifyouarepassingthefilenamedirectlytothescript: perlgoat.pl"C:\GoatKids\goat.txt" Share Improvethisanswer Follow editedAug18,2011at1:52 answeredAug17,2011at2:27 SmartnorSmartnor 5144bronzebadges 3 1 Careful,singlequotesdon'tmeanthesamethinginaWindowscommandlineastheydoinaUnixshell.Ifyoutypeperlgoat.pl'C:\GoatKids\goat.txt'inaWindowscommandshell,goat.plwillseeanargumentwithsinglequotes. – KeithThompson Aug17,2011at2:40 Icorrectedit.Thanks.Igenerallydonotusecommandlineoptionsbecausemostofmyusersjustwanttodouble-clickthescripttorunit.However,Iwritescriptsthatcallfunctionswithfilenamesasparametersonaveryfrequentbasis. – Smartnor Aug17,2011at3:12 1 WelcometoStackOverflow.Thisisaquestionandanswersite,notanewsgroupordiscussionforum.Itworksbysomeoneaskingaquestion,andthenpeoplecanpostanswerstothequestionbytypingintothe"YourAnswer"area.Yourpostisnotananswertothequestionasked("Iagreetheotheranswersaregood"),andshouldnotappearasone.Ifyouhaven'talready,pleasetakeafewminutestoreadtheFAQandafewotherquestionstoseehowthesiteisdesignedtowork.Thanks. – KenWhite Aug18,2011at1:06 Addacomment  |  4 Thepreviousanswershavedescribedhowshiftworks.Iwouldliketocommentonwhyitisagoodideatouseitinyourownprograms. Perlbydefaultisapass-by-referencelanguage.Ifasubroutinemodifiesitsargument,thecallerwillseethese,sometimesunexpected,changes.Itisagoodpracticetouseshifttoassignasubroutineargumenttoaprivatevariable.Thisway,ifyoumakeanychangestoit,itwillnotbevisibletothecaller.E.g.,thecodebelowoutputs 1 2 2 Thefirstsubroutinemodifiesitsargumentandthecallerseesthechange.Thesecondsubroutinemodifiesaprivatecopyofitsargument,andthischangeisnotvisibleinthecaller. usestrict; usewarnings; subpass_by_ref{ $_[0]=2; } subpass_by_value{ my$x=shift@_; $x=3; } my$x=1; print$x,"\n"; pass_by_ref($x); print$x,"\n"; pass_by_value($x); print$x,"\n"; Share Improvethisanswer Follow answeredAug17,2011at21:32 user335958user335958 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?Browseotherquestionstaggedperlvariablesoraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Linked 77 Whatdoesshift()doinPerl? 1 Assigningshifttoavariable Related 7622 HowdoJavaScriptclosureswork? 983 WhatisthenamingconventioninPythonforvariableandfunction? 1230 HowtotrimwhitespacefromaBashvariable? 2174 WhatisthescopeofvariablesinJavaScript? 2014 HowdoIcheckifavariableisanarrayinJavaScript? 1267 HowdoIcheckifavariableexists? 2551 HowcanIdetermineifavariableis'undefined'or'null'? 2206 HowtocheckifavariableissetinBash 1337 "Notice:Undefinedvariable","Notice:Undefinedindex","Warning:Undefinedarraykey",and"Notice:Undefinedoffset"usingPHP 2250 JavaScriptcheckifvariableexists(isdefined/initialized) HotNetworkQuestions Isthereawayasocietycouldproducetanksascheaplyascars? Whataredisadvantagesofaerodropbars? WhyareringsnotafavoriteoptioninITnetworks? WhatexactlywerethoselargeorangechipsontheHayesMicromodemIIinterfacecard? Idealprogramminglanguageforanoperationsresearcher Changingnumberformatsinstrings Mylibrarymembershipnumber Whydoweneedmixedstatesinquantummechanics? WhydoesMOS6502requireanexternalclockifithasaninternaloscillator? Doesaparallelairgapincreaseordecreasemaximumenergystoredinmagneticfieldofaninductor? DoGFI/GFCIoutletshaveapotentialtodamageNespressomachines(andcoffeemachines?) Howisitpossibletofiltereitherhighorlowfrequenciesofasinglesinewave? DidtheDudeeverhaveanoccupationotherthanunemployed? Howdopropellanttransfertechnologieswork? Isthephrasestill"cuantosañostiene"wheretheageisobviouslylessthanoneyear? HowdoyoudescribesomeoneasashapeshifterinLatin? AlphabetChecksum FindingTheveninresistanceforabridgecircuitwithvoltagesource HowtoinstallLunarVimonWindows? Basaltsill-acontradictioninterms? Shouldmy240velectricstovebegroundedtotheneutrallikethis? Mysuperpowersonlyworkatnight,howdoIstopcriminalsfromjustdoingcrimeinthemorningtoavoidme? Wouldlanguagehavemeaningiftherewasnoconsciousness? EquilibriumconstantvsReactionrateconstant morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?