How should I use the "my" keyword in Perl? - Stack Overflow
文章推薦指數: 80 %
my restricts the scope of a variable. The scope of a variable is where it can be seen. Reducing a variable's scope to where the variable is ... 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 HowshouldIusethe"my"keywordinPerl? AskQuestion Asked 8years,9monthsago Modified 7years,9monthsago Viewed 93ktimes 101 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. Ikeepseeingthe"my"keywordinfrontofvariablenamesinexamplePerlscriptsonlinebutIhavenoideawhatitmeans.ItriedreadingthemanualpagesandothersitesonlinebutI'mhavingdifficultydiscerningwhatitisforgiventhedifferencebetweenhowIseeitusedandthemanual. Forexample,itsusedtogetthelengthofthearrayinthispost: FindsizeofanarrayinPerl Butthemanualsays: Amydeclaresthelistedvariablestobelocal(lexically)tothe enclosingblock,file,oreval.Ifmorethanonevalueislisted,the listmustbeplacedinparentheses. Whatdoesitdoandhowisitused? perlscopedeclaration Share Follow editedMay23,2017at11:47 CommunityBot 111silverbadge askedJan2,2014at18:43 FistOfFuryFistOfFury 6,38777goldbadges4545silverbadges5757bronzebadges 2 3 Re"itsusedtogetthelengthofthearrayinthispost",Notatall.mydidnotfactorintoitintheleast.It'sthescalarassignmentoperator(=)thatenforcedthescalarcontexton@arr. – ikegami Jan2,2014at20:03 Ifit'snotreally"yours",youshouldnotuseit. – icenac Jan23,2017at14:26 Addacomment | 3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 153 myrestrictsthescopeofavariable.Thescopeofavariableiswhereitcanbeseen.Reducingavariable'sscopetowherethevariableisneededisafundamentalaspectofgoodprogramming.Itmakesthecodemorereadableandlesserror-prone,andresultsinaslewofderivedbenefits. Ifyoudon'tdeclareavariableusingmy,aglobalvariablewillbecreatedinstead.Thisistobeavoided.Usingusestrict;tellsPerlyouwanttobepreventedfromimplicitlycreatingglobalvariables,whichiswhyyoushouldalwaysuseusestrict;(andusewarnings;)inyourprograms. Relatedreading:Whyuseusestrict;andusewarnings;? Share Follow editedMay23,2017at12:10 CommunityBot 111silverbadge answeredJan2,2014at20:00 ikegamiikegami 352k1515goldbadges254254silverbadges499499bronzebadges 5 13 Finallyananswerthatexplainswhy. – ThisSuitIsBlackNot Jan2,2014at21:18 ForpeoplecomingherefromJS:It'sessentiallylikevarandletinJavaScript.Without'usestrict';JSwillletyoudeclarenewglobalvariableswithouteitherkeyword,whichisn'tconsideredthebestofpractices. – ElectricCoffee Aug10,2020at7:25 @ElectricCoffee,InJSterms,thequestionwouldbe"Whatdoesletandvardoandhowshouldtheybeused?"Andyes,theanswerwouldberoughlythesame.(JS'sletvarsarealotlikePerl'smyvars,exceptthatletvarscan'tbecaptured.) – ikegami Aug10,2020at7:52 1 IjustmeantthatifpeoplecametoPerlfromJS,itwouldbeaneasywaytoexplainthesameconcept – ElectricCoffee Aug10,2020at8:32 @ElectricCoffee1)Aprogrammerthatunderstandsscopingdoesn'tneedtohaveitexplainedtothemagainafterswitchinglanguages.2)Notsurethatyouactuallydidexplainscoping,intermsaJSprogrammerwouldunderstandorotherwise.Maybeyouweretryingtoexplainusestrict;?Butthatwasn'tthequestion,andusestrict;doesmorethanthat.Ormaybeyoumeanttocommunicatethatmylimitsthescopeofvarskindalikeletandvardo,butthat'sprettymuchthefirstsentenceoftheanswer.3)Ifyouwishtoansweraquestiondifferently,that'swhatAnswersarefor. – ikegami Aug10,2020at8:52 Addacomment | 31 Quicksummary:mycreatesanewvariable,localtemporarilyamendsthevalueofavariable Intheexamplebelow,$::arefersto$ainthe'global'namespace. $a=3.14159; { my$a=3; print"Inblock,\$a=$a\n"; print"Inblock,\$::a=$::a\n"; } print"Outsideblock,\$a=$a\n"; print"Outsideblock,\$::a=$::a\n"; #Thisoutputs Inblock,$a=3 Inblock,$::a=3.14159 Outsideblock,$a=3.14159 Outsideblock,$::a=3.14159 ie,localtemporarilychangesthevalueofthevariable,butonlywithinthescopeitexistsin. Source:http://www.perlmonks.org/?node_id=94007 Update Aboutdifferencebetweenourandmypleasesee WhatisthedifferencebetweenmyandourinPerl? (ThankstoThisSuitIsBlackNot). Share Follow editedMay23,2017at12:34 CommunityBot 111silverbadge answeredJan2,2014at18:46 IgorChubinIgorChubin 58.7k1010goldbadges117117silverbadges139139bronzebadges 4 2 Ithinkthisanswerneedssomeadjusting.Youhaveacodeexampledemonstratingtheuseofmy,butthenfollowthatupwithasentencetalkingaboutlocalasifyouhadjustdemonstratedlocal'suse,despitethatlocalisnotdemonstratedanywhereinthisanswer.IthinkyoukindofmisquotedthesourceonPerlMonks,whichhastwocodeexamples.Thesentenceaboutlocalwasdescribingtheotherone,nottheoneyoutranscribedhere. – temporary_user_name May17,2017at8:01 1 Whyevenmentionlocalwhenyoudon'tuseitinthecodeexample? – Greenonline Dec16,2020at15:48 @Greenonline:Withthislogic,ifyouhavenocodeexampleatall,youshouldn'tmentionanything? – IgorChubin Dec16,2020at21:31 Wellyes.Asmentionedinthiscomment,thecodeexamplethatyougivedoesn'tshowtheuseoflocal.However,youthenexplainthescopeoflocal,butithasn'tbeendemonstrated.Theproblemisthatyou'vecopiedthewrongcodesnippetfromtheperlmonkspage.It'srathermisleading. – Greenonline Jan14,2021at9:35 Addacomment | 6 PrivateVariablesviamy()istheprimarydocumentationformy. Inthearraysizeexampleyoumention,it'snotusedtofindthesizeofthearray.It'susedtocreateanewvariabletoholdthesizeofthearray. Share Follow answeredJan2,2014at18:47 cjmcjm 60.9k99goldbadges125125silverbadges173173bronzebadges 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?Browseotherquestionstaggedperlscopedeclarationoraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Linked 270 FindsizeofanarrayinPerl 204 Whatisthedifferencebetween'my'and'our'inPerl? 110 Whyusestrictandwarnings? 5 WhyisthedefaultscopingbehaviorinPerlthewaythatitis? 3 InPerl,do"$a"and"$b"haveanyspecialuseoutsideofthesort()function? 3 HowtodoPerlstatemachine(FSM)toparsebitstream(bytesequence)? -1 HowcanIuseperltodeletefilesmatchingaregex 2 Whyisaregularexpressioncontainingtheexactstringnotmatchingsuccessfully? 2 Whathappenswheninsteadofcreatingvariableswith'my',youonlyspecifythenameofthevariableinPerl? -4 What'sthedifferenceinthesetwoarraydeclarations? Seemorelinkedquestions Related 7622 HowdoJavaScriptclosureswork? 2187 WhenshouldIuse'self'over'$this'? 2174 WhatisthescopeofvariablesinJavaScript? 5940 Whatisthedifferencebetween"let"and"var"? 943 What’sthedifferencebetween"Array()"and"[]"whiledeclaringaJavaScriptarray? 749 HowtofixalocalesettingwarningfromPerl 585 WhydoesmodernPerlavoidUTF-8bydefault? 1819 IsthereareasonforC#'sreuseofthevariableinaforeach? 6 IsitgoodtousemywithloopsinPerl? 383 Whatisthe'open'keywordinSwift? HotNetworkQuestions Selectrankofsinglerow Op-ampswithnegativefeedbackanddifferentialamplifiers.What'sthedifference? Robbersinastandoff Howtohelpadev,whoisotherwisegood,improvethespeedatwhichtheywork? Howtoobtainaminor'spassportwithanabsentparent HowdoIcreategeometry/texturesforproceduralshading? Whydocourtopinionslistmultiplelayersofcitations? Bootablefloppydisk EquilibriumconstantvsReactionrateconstant Whatisanaxiomatizationoftheequality-freetheoryofantisymmetricrelations? WouldaTrump-nominatedSupremeCourtjusticebeexpectedtorecusethemselvesfromaTrumpcase? DidtheDudeeverhaveanoccupationotherthanunemployed? IsGoogleStreetViewcoverageinGermanyexpectedtoincrease? ObtaincoordinatesfromGeometricTransformation Whatactuallyareline-drivenwinds? Whatis"gallowsflesh?" WhereisthisparkinMontreal,withautumncolortreesandpond? WhoorwhatcreatedtheT'au? WhatexactlywerethoselargeorangechipsontheHayesMicromodemIIinterfacecard? WhywasThor'shammerneverusedagain? Whatisthelargestpossiblegunamanwithsuperstrengthcanuse? WhyisthePassivevoiceof"einladen"usedwith"sein"andnotwerden? Graphingfloorandceilingfunctions WhyareringsnotafavoriteoptioninITnetworks? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Perl 學習手札- 12. 字串處理- Easun.org 镜像
my $mainstring = "Perl Mongers"; my $substring = "Mongers"; print index($mainstring, $substring);...
- 2Perl my Function - Tutorialspoint
Perl my Function, This function declares the variables in LIST to be lexically scoped within the ...
- 3perl 在函數中宣告my $_ | 人生海海
以前在學Perl 時,知道在函數中宣告變數可以用local 或my ,local 表示在 ... 結果程式有不在預期中的結果,還debug 半天,才發現就是my $_ 造成的。
- 4Perl 變數的作用my, our, local和全域變數_Perl
perl定義的變數預設是全域1)my 作用:把變數的名字和值都限於某個範圍內,也就是說,該變數只能本層模組或者函數可以看到這個變數,高一層或者低一層 ...
- 5Perl | my keyword - GeeksforGeeks
my keyword in Perl declares the listed variable to be local to the enclosing block in which it is...