Establishing a Default Value - Perl Cookbook [Book] - O'Reilly

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

If 0 or "0" are valid values for your variables, use defined instead: ... If 0 is a valid value for $ARGV[0] , we can't use || because it evaluates as false ... Skiptomaincontent PerlCookbookby GetfullaccesstoPerlCookbookand60K+othertitles,withfree10-daytrialofO'Reilly. There'salsoliveonlineevents,interactivecontent,certificationprepmaterials,andmore. Startyourfreetrial EstablishingaDefaultValueProblem Youwouldliketogiveadefaultvaluetoascalarvariable,butonly ifitdoesn’talreadyhaveone.Itoftenhappensthatyouwant ahard-codeddefaultvalueforavariablethatcanbeoverriddenfrom thecommand-lineorthroughanenvironmentvariable.SolutionUsethe|| or||=operator, whichworkonbothstringsandnumbers:#use$bif$bistrue,else$c $a=$b||$c; #set$xto$yunless$xisalreadytrue $x||=$yIf0or"0"arevalidvalues foryourvariables,use defined instead:#use$bif$bisdefined,else$c $a=defined($b)?$b:$c;DiscussionThebigdifferencebetweenthetwotechniques (definedand||)iswhatthey test: definednessversustruth.Threedefinedvaluesarestillfalseinthe worldofPerl:0,"0",and"". Ifyourvariablealreadyheldoneofthose,andyouwantedtokeep thatvalue,a||wouldn’twork.You’d havetousetheclumsiertestswithdefined instead.It’softenconvenienttoarrangeforyourprogramto careonlyabouttrueorfalsevalues,notdefinedorundefinedones.Ratherthanbeingrestrictedinitsreturnvaluestoamere1or asinmostotherlanguages,Perl’s|| operatorhasamuchmoreinterestingproperty:Itreturnsitsfirst operand(theleft-handside)ifthatoperandistrue;otherwiseit returnsitssecondoperand.The && operatoralsoreturnsthelast evaluatedexpression,butislessoftenusedforthisproperty.These operatorsdon’tcarewhethertheiroperandsarestrings, numbers,orreferences—anyscalarwilldo.Theyjustreturnthe firstonethatmakesthewholeexpressiontrueorfalse.This doesn’taffecttheBooleansenseofthereturnvalue,butit doesmaketheoperatorsmoreconvenienttouse.Thispropertyletsyouprovideadefaultvaluetoavariable, function,orlongerexpressionincasethefirstpartdoesn’t panout.Here’sanexampleof||,which wouldset$footobethecontentsofeither $baror,if$barisfalse, "DEFAULT VALUE“:$foo=$bar||"DEFAULTVALUE";Here’sanotherexample,whichsets$dirto beeitherthefirstargumenttotheprogramor "/tmp"ifnoargumentwasgiven.$dir=shift(@ARGV)||"/tmp";Wecandothiswithoutaltering@ARGV:$dir=$ARGV[0]||"/tmp";If0isavalidvaluefor $ARGV[0],wecan’tuse|| becauseitevaluatesasfalseeventhoughit’savaluewewant toaccept.Wemustresorttotheternary(“hook”) operator:$dir=defined($ARGV[0])?shift(@ARGV):"/tmp";Wecanalsowritethisasfollows,althoughwithslightlydifferent semantics:$dir=@ARGV?$ARGV[0]:"/tmp";[email protected] thehookoperatorasaconditionina?:statement [email protected]’sonly falsewhenthereare elements,inwhichcaseweuse"/tmp".Inall othercases(whentheusergivesanargument),weusethefirst argument.Thefollowinglineincrementsavaluein%count, usingasthekeyeither$shellor,if $shellisfalse,"/bin/sh".$count{$shell||"/bin/sh"}++;Youmaychainseveralalternativestogetheraswehaveinthe followingexample.Thefirstexpressionthatreturnsatruevalue willbeused.#findtheusernameonUnixsystems $user=$ENV{USER} ||$ENV{LOGNAME} ||getlogin() ||(getpwuid($



請為這篇文章評分?