批處理函數遞歸解惑

參考:https://www.dostips.com/DtTutoFunctions.php#FunctionTutorial.RecursiveFunctions
最近做svn工具發現批處理能用遞歸很好奇的研究了一下,網上找了幾個實例,但自己一寫就總是不對,記錄一下,主要是對批處理理解不深入

批處理遞歸主要用setlocal命令來緩存原來的變量 使用endlocal 後再還原原來的變量 達到不相互影響的效果

@echo on
prompt $G
setlocal enabledelayedexpansion
set mystring=1xxxx
set /a sLength=0
call :strLen sLength %mystring%
echo mystring=%mystring% sLength=%sLength%
pause

:strLen
if "%~2" equ "" set lenName=0 & goto :eof rem empty string process
setlocal
set /a lenName=%~1
set str=%~2
if "!str:~%lenName%!" neq "" set /a NextLen=lenName+1  &call :strLen NextLen,%str%
(endlocal &set /a %~1=%NextLen%)
goto :eof

pause
遞歸完成後再返回來的值 是通過一個專門的變量名來層層傳遞的
關鍵句是

(endlocal &set /a %~1=%NextLen%)
&這個運算符不能省 意思是在一行執行

結束當前的塊,這樣程序恢復上次的變量 
set /a %~1=%NextLen% 相當於把當前結果往上傳

這樣一層一層往上返回 達到了目的


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章