Let's say you write a function or procedure or sub program or whatever you want to call it in batch. How do you pass back a value to the caller? You can of course set an environment variable, but that's like setting a global variable. And that's not very nice if you need to call the function multiple times and only use the value after all function calls are made.
Consider this example:
@echo off
call :GETVALUE
set INPUT1=%USERINPUT%
call :GETVALUE
set INPUT2=%USERINPUT%
echo %INPUT1% %INPUT2%
goto :EOF
:GETVALUE
set /P USERINPUT=Input?
goto :EOF
Like I said, it's doable, but not very nice. I find it more soothing to the eyes if I can pass the variable name as an argument to the function. And here's how you do it:
@echo off
call :GETVALUE INPUT1
call :GETVALUE INPUT2
echo %INPUT1% %INPUT2%
goto :EOF
:GETVALUE
set /P %1=Input?
goto :EOF
Nice and simple. All you need to do is remember that you can use %1 and other %<number> on the left hand side of an assignment. And it makes you think for a second that you are programming a real scripting language.
No comments:
Post a Comment