What does =~/^0$/ mean in Perl? - Stack Overflow

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

Sound like that perl script is an awesome piece of code. =~ /^0$/ is a regular expression applied to the contents of $arr[$i] . 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 Whatdoes=~/^0$/meaninPerl? AskQuestion Asked 9years,4monthsago Modified 9years,4monthsago Viewed 2ktimes 2 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. I'mnewtoPerlandIhavebeenlearningaboutthePerlbasicsforpasttwodays. I'mconvertingaPerlscripttoJavaprogramgradually. InthePerlscript,Icameacrossthiscode. if($arr[$i]=~/^0$/){ ... ... } Iknowthat$arr[$i]meansgettingtheithelementfromthearrayarr. Butwhatdoes=~/^0$/mean? Towhataretheycomparingthearray'selement? Isearchedforthis,butIcouldn'tfindit. Someonepleaseexplainme. FYI,thearrcontainsfloatingvalues. perl Share Improvethisquestion Follow askedMay29,2013at13:47 BaranitharanSelvasundaramBaranitharanSelvasundaram 14011silverbadge1111bronzebadges 2 4 Soundlikethatperlscriptisanawesomepieceofcode.=~/^0$/isaregularexpressionappliedtothecontentsof$arr[$i].Ittriestocheckwhetherthecontentsis0. – innaM May29,2013at13:50 1 @innaM/^0$/alsomatches"0\n" – mob May29,2013at16:15 Addacomment  |  3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 10 if($arr[$i])=~/^0$/)isroughlyequivalenttoif($arr[$i]eq"0"),butnotexactlythesame,asitwillmatchboththestrings"0"and"0\n".If$arr[$1]wasreadfromafileorstdinandithasnotbeenchomped,thiscanbeaverysignificantdistinction. if($arr[$i]==0),ontheotherhand,willmatchanystringbeginningwithanon-numericcharacterorastringofzeroes/whitespacewhichisnotfollowedbyanumericcharacter,althoughitwillgenerateawarningifthestringcontainsnon-whitespace,non-digitcharactersorcontainsonlywhitespace(andwarningsareenabled,ofcourse). Share Improvethisanswer Follow editedMay30,2013at8:23 answeredMay29,2013at14:13 DaveSherohmanDaveSherohman 44.6k1313goldbadges6565silverbadges9999bronzebadges 3 1 "followedbyanon-numericcharacter"?no.""==0,and"000"==0.also,warningsaren'tdependentonjustthefirstnon-whitespacecharacter. – ysth May29,2013at17:03 @ysth:Fairpoints.Editedtomorecloselyapproximatereality. – DaveSherohman May30,2013at8:24 It'sgreatthatyoupointouttheimportantdifferencebetweenthisand$arr[$i]eq"0",would+20ifIcould! – zx81 Jun6,2014at22:03 Addacomment  |  9 =~isabindingoperator. "Binary"=~"bindsascalarexpressiontoapatternmatch" /^0$/ontherighthandsideistheregex ^Matchthebeginningoftheline $Matchtheendoftheline(orbeforenewlineattheend) Andthezerohasnospecialmeaning. Share Improvethisanswer Follow answeredMay29,2013at13:59 chrsblckchrsblck 3,89022goldbadges1717silverbadges2020bronzebadges Addacomment  |  9 ^and$areregexanchorswhichsays$arr[$i]shouldbeginwith0andthereisendofstringimmediatelyafterit. Itcanbewrittenas if($arr[$i]eq"0"or$arr[$i]eq"0\n") Share Improvethisanswer Follow editedMay29,2013at16:18 answeredMay29,2013at13:51 mpapecmpapec 49.8k88goldbadges6464silverbadges122122bronzebadges 4 3 Whether'evenbetter'isbetterdependsonhowhappyyouarethatit'struemoreoftenthantheoriginal.'Better'isbest,absentusere,(textual)parallelism,andthewriterreckoninghemayreturntothistesttoaddtotheregex. – JulianFondren May29,2013at14:03 4 The"evenbetter"versionisaterribleidea,sinceitwillbetruewhen$arr[$i]isanynon-numericstring,like"helloworld". – NathanielWaisbrot May29,2013at14:06 Thanks,updated.Attheend,authorknowsbestwhatheputin$arr[$i]andwhetherthereshouldbestringornumber. – mpapec May29,2013at14:07 1 /^0$/alsomatches"0\n" – mob May29,2013at16:14 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?Browseotherquestionstaggedperloraskyourownquestion. TheOverflowBlog IntroducingtheOverflowOfflineproject Hehelpedbuild.NETandVSCode—Now’sheworkingonWeb3(Ep.499) FeaturedonMeta The2022Community-a-thonhasbegun! Mobileappinfrastructurebeingdecommissioned CollectivesUpdate:RecognizedMembers,Articles,andGitLab The[script]tagisbeingburninated StagingGroundWorkflow:CannedComments Visitchat Related 749 HowtofixalocalesettingwarningfromPerl 585 WhydoesmodernPerlavoidUTF-8bydefault? 1 Perl:UnusualRegExp 7 Whatdoes"my($self,%myInputs)=@_;"mean? 4 Whatdoes$$inperlactuallyreturn? 1 Whatdoes|.*/||doinPerlregexsubstitution? 0 Whatdoesexec${PERL-perl}-Sx$0${1+"$@"}meaninShellscript? HotNetworkQuestions Robbersinastandoff HowcanIconnectTikZnodeswithmultiple-cornerlines? Linuxfilesystemsforcode-compilation,whichperformbest? Idealprogramminglanguageforanoperationsresearcher Howtohelpadev,whoisotherwisegood,improvethespeedatwhichtheywork? Whywouldatechnologicallyadvancedsocietyusehumancontrollerstodirectspaceshiptraffic? Whatisthemostefficientwaytoget110Vfrom220Vsingle-phasewiring? Misuseofmixedeffectsmodel Whyarefangsofgirlssocommoninanime? WhereisthisparkinMontreal,withautumncolortreesandpond? Isthephrasestill"cuantosañostiene"wheretheageisobviouslylessthanoneyear? FindingTheveninresistanceforabridgecircuitwithvoltagesource WhatexactlywerethoselargeorangechipsontheHayesMicromodemIIinterfacecard? scalingdiagramsinatable Whatactuallyareline-drivenwinds? Wouldlanguagehavemeaningiftherewasnoconsciousness? EquilibriumconstantvsReactionrateconstant TeXpointcommand Pianochordswithanoctaveinthem DoRSAsignaturesreallyneedpadding? ShouldItellmyadvisormyfianceleftme? HowcanIkeeptheexistingguideswhentheunderlyingfileisupdatedinPhotoshop? Isthereawayasocietycouldproducetanksascheaplyascars? Whenisitokaytobreakapinusingkingsidepawns? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?