perl + identify if param is empty value from ARG - Stack Overflow

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

How to identify if $param is a null value or empty value, same as [ -z from ksh? #!/usr/bin/perl my $param = $ARGV[0]; if ($param = ... 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 perl+identifyifparamisemptyvaluefromARG AskQuestion Asked 12years,3monthsago Modified 4years,11monthsago Viewed 22ktimes 2 New!Savequestionsoranswersandorganizeyourfavoritecontent.Learnmore. whenIrunthefollowingscript.plscriptwithnoarguments: ./script.pl IdonotgetthemessageNoarg.Why?Howtoidentifyif$paramisanullvalueoremptyvalue,sameas[-zfromksh? #!/usr/bin/perl my$param=$ARGV[0]; if($param=""){ printNoarg; }else{ printarg:$param; } perl Share Follow editedJul27,2010at8:13 daxim 38.9k44goldbadges6363silverbadges129129bronzebadges askedJul27,2010at8:07 lidialidia 2,9431414goldbadges4141silverbadges4747bronzebadges 2 1 $#ARGV==-1istheeasiest.perldoc.perl.org/perlvar.html#%40ARGV – msw Jul27,2010at8:17 butifARGV[1];isnullorARGV[2];howtocompareparamwith..? – lidia Jul27,2010at8:22 Addacomment  |  5Answers 5 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 11 Becauseit'snotPerl.Wheredidyoulearnthatsyntax?Somuchiswrongwithit. $param=""assignsanemptystringto$param,that'snotwhatyouwant. nullisspelledundefinPerl. Tocomparestrings,usetheeqoperator. Youmustquotestrings:print"Noarg" Mucheasier: #!/usr/bin/perl if(@ARGV){ print'haveparameters'; }else{ printq{don'thaveparameters}; } Share Follow answeredJul27,2010at8:30 daximdaxim 38.9k44goldbadges6363silverbadges129129bronzebadges 6 butifIhaveARG1andnotARG2Igetthedon'thaveparameters? – lidia Jul27,2010at8:39 Inearlymadethatsamesuggestion,butI'mguessingtheOPwantstoextendtohandledifferentnumbersofarguments,andthentestingthelengthof@ARGVisn'tquitesotidy. – AndyMortimer Jul27,2010at8:43 Justtryitandsee.Whenyoupassanyparametersonthecommand-line,@ARGVisfilledwithvaluesandtheprogramgoesintothefirstbranch. – daxim Jul27,2010at8:46 canyougivemeexampleforthatTHX – lidia Jul27,2010at8:52 whyneedtoprintq{don'thaveparameters};andnotprint"don'thaveparameters"?? – lidia Jul27,2010at8:54  |  Show1morecomment 5 Hereisanexampletoillustrateitabitbetter. if($#ARGV==-1){ print"Noargumentspassed.\n"; }elseif($#ARGV==0){ print"Oneargumentpassed.\n"; }else{ print$#ARGV+1."argumentspassed.\n"; } Ilikeusing"scalar@ARGV"asthisrepresentsnumberofelementsinanarray.$#ARGV,instead,istheindexoflastelementinthearray.Thisiswhyitisoffbyone.If$[(thisisaspecialvariablethatsetsthestartingindexofPerlarrays.)wassetto1andnot0(thedefault),then$#ARGVwouldnotbeoffbyoneforourpurposes.Iwouldnotmesswith$[asitisaglobal.Changingmaybreakalotmodules. my$argument_count=scalar@ARGV; if($argument_count==0){ print"Noargumentspassed.\n"; }elseif($argument_count==1){ print"Oneargumentpassed.\n"; }else{ print"$argument_countargumentspassed.\n"; } Share Follow editedJul29,2010at13:52 answeredJul29,2010at13:40 gdeygdey 14155bronzebadges Addacomment  |  2 OK,itseemspeoplefoundmypreviousanswermis-leading,sohere'sanothertry,moredirectlythistime. Thetestyou'relookingforisdefined: my$param=$ARGV[0]; if(defined$param){ print"arg:$param\n"; }else{ print"Noarg\n"; } Ifthereweren'tenoughparameterstofillin$ARGV[0](orotherlaterelements)thevalueinthatpositionwillbeundef,sothedefinedtestwillevaluatetofalse. Share Follow answeredJul28,2010at8:37 AndyMortimerAndyMortimer 3,4991919silverbadges1414bronzebadges Addacomment  |  0 ifparamisemptyyoucanautomakeaparamval: $ARGV[0]||'yourParam'; Share Follow answeredJun17,2013at8:47 GankGank 5,35144goldbadges4848silverbadges4545bronzebadges Addacomment  |  0 Here'sconvenientsnippettomakeascriptabortwithanerrorifnoargumentsarepassed: if(notdefined$ARGV[0]){ printSTDERR"Error:missingparameter.Usage:perl$0\n"; exit1; } (Therearemorecompactandmoreverbose/robustwaystowritethis,butasaPerlnovice,Ifoundthistoofferagoodbalanceofclarityandconciseness.) Share Follow answeredNov11,2017at13:17 waldyriouswaldyrious 3,44544goldbadges3333silverbadges3939bronzebadges 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 Linked -1 perl+@ARGV+printsyntax Related 749 HowtofixalocalesettingwarningfromPerl 38 HowcanIdebugaPerlscript? 0 perl:forcetheuseofcommandlineflags? 17 HowtocallapythonscriptfromPerl? 0 perl+perlscriptlocationunder/etc/rc3.dwithdiffresults 1 callperlscriptfrompythonworksincommands.getstatusoutputbutnotinsubprocess.call 0 CannotcallperlscriptfromJava 0 PassArgstoChildScriptFromPerl 2 Isthereawaytoidentifywhichperlspecificoptionsarepassedtoascript? HotNetworkQuestions HowdoyoudescribesomeoneasashapeshifterinLatin? Isthereamore"physicallymature"waytothinkabouttherighthandrulewithelectromagnetism? Makegraduatedsymbolvaluesexceedwhatexistsinthedata Isthephrasestill"cuantosañostiene"wheretheageisobviouslylessthanoneyear? Robbersinastandoff Minimumrotationtogetthemaximumvalue Istriplebranchingnecessaryinmakingasyntaxtreefor'thegirlintheroomwavedtome'? WorkplaceSafetyPolicyMakesMeLessSafe Nomatchingfunctionforcallto'DS3231(constuint8_t&,constuint8_t&) WhatcanIdoaboutplayerswho"cheat"whenansweringtheendofsessionquestions? Whattodoafterapuremathacademicpath? Arelawswrittenlogicallyandrigorously? WhatkindofcivilactioniscreatedbytheTexasHeartbeatAct? ShouldItellmyadvisormyfianceleftme? Linuxfilesystemsforcode-compilation,whichperformbest? Changingnumberformatsinstrings Smpswithswitchingstageaftertransformer WhereisthisparkinMontreal,withautumncolortreesandpond? CanIpublishmythesisonlineandgetpaid? Whydoweneedmixedstatesinquantummechanics? Isablackmoonpossible? WhatexactlywerethoselargeorangechipsontheHayesMicromodemIIinterfacecard? Graphingfloorandceilingfunctions WhyisthePassivevoiceof"einladen"usedwith"sein"andnotwerden? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-perl Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?