DOS批处理 函数定义与用法
Whatitis,whyit`simportantandhowtowriteyourown.
Description:Theassumptionis:Abatchscriptsnippetcanbenamedafunctionwhen:
1....ithasacallableentrancepoint.
2....oncompletionexecutioncontinuesrightafterthecommandthatinitiallycalledthefunction.
3....itworksthesamenomatterfromwhereit`sbeingcalled,evenwhenitcallsitselfrecursively.
4....thevariablesusedwithinafunctiondonotconflictwithvariablesoutsidethefunction.
5....itexchangesdatawiththecallingcodestrictlythroughinputandoutputvariablesorareturncode.
Thebenefitsbehindfunctionsare:
1.Keepthemainscriptclean
2.Hidecomplexityinreusablefunctions
3.Testfunctionsindependentlyfromthemainscript
4.Addmorefunctionalitytoyourbatchscriptsimplybyaddingmorefunctionsatthebottom
5.Don`tworryaboutthefunctionimplementation,justtestitanduseit
CreateaFunctionWhatisafunction?
CallaFunctionHowtoinvokeafunction?
Example-CallingaFunctionAnExampleshowinghowitworks.
PassingFunctionArgumentsHowtopassargumentstothefunction?
ParsingFunctionArgumentsHowtoretrievefunctionargumentswithinthefunction?
Example-FunctionwithArgumentsAnExampleshowinghowitworks.
ReturningValuestheClassicWayTheclassicwayofreturningvaluesandthelimitations.
ReturningValuesviaReferencesLetthecallerdeterminehowtoreturnthefunctionresultandavoidtheneedofdedicatedvariables.
Example-ReturningValuesusingVariableReferenceAnExampleshowinghowitworks.
LocalVariablesinFunctionsHowtoavoidnameconflictsandkeepvariablechangeslocaltothefunction?
ReturningLocalVariablesHowtopassreturnvaluesovertheENDLOCALbarrier?
RecursiveFunctionsTadaaah!!!
SummaryDefiningastandardformatforaDOSbatchfunction
DOSBatch-FunctionTutorialWhatitis,whyit`simportantandhowtowriteyourown.
CreateaFunction-Whatisafunction
Description:InDOSyouwriteafunctionbysurroundingagroupofcommandbyalabelandaGOTO:EOFcommand.Asinglebatchfilecancontainmultiplefunctionsdefinedlikethis.Thelabelbecomesthefunctionname.
Script:
:myDosFunc -herestartsmyfunctionidentifiedbyit`slabel echo.herethemyDosFuncfunctionisexecutingagroupofcommands echo.itcoulddoalotofthings GOTO:EOF
CallaFunction-Howtoinvokeafunction
Description:AfunctioncanbecalledwiththeCALLcommandfollowedbythefunctionlabel.
Script:01.
call:myDosFunc
Example-CallingaFunction-AnExampleshowinghowitworks
Description:Theuseofbatchfunctionswilldividethescriptintotwosections.
1.Themainscript:startingatline1endingwithaGOTO:EOFcommandthatterminatesthescript.
2.Thefunctionsection:fillingthesecondhalfofthebatchfilewithoneormorefunctionstobecallablefromthemainscript.
Script:
@echooff echo.goingtoexecutemyDosFunc call:myDosFunc echo.returnedfrommyDosFunc
echo.&pause&goto:eof
::-------------------------------------------------------- ::--Functionsectionstartsbelowhere ::--------------------------------------------------------
:myDosFunc -herestartsmyfunctionidentifiedbyit`slabel echo. herethemyDosFuncfunctionisexecutingagroupofcommands echo. itcoulddoalotofthings goto:eof