Thursday 17 July 2008

Batch Programming Tip#10: Making and calling a subroutine (part 1)

It looks like quite a few people are wondering how to write a subroutine, and how to pass it arguments. So let's write a small subroutine. You can't actually 'return' a value from the subroutine in the usual sense of the term. You can however set one or more variables within the subroutine which can then be used by the caller.

Let's imagine we need to write a subroutine that will retrieve the current date for us.

Let's start our batch by writing the following subroutine which will compute the date and store it in the %_date% variable.

@echo off

:get_date
for /F "tokens=2 delims= " %%d in ('date /T') do (
set _date=%%d
)
goto blackhole

:blackhole

What happens here is a slightly more complex for /F construct than we saw previously.
date /T outputs the current date, for instance as follows: mon. 14/07/2008
The for construct then effectively splits the string using the space character as the delimiter (this will leave us with 2 tokens: 'mon.' and '14/07/2008' but without the quotes). It then takes the second token (tokens=2) which is stored in %%d. Neat!

Obviously, if you run this script 'as-is', you won't actually 'see' anything happen, although the script will have computed the 'date' and stored it in the %_date% variable.

I do have an inkling that date format varies according to system locale. For instance you may find that on some systems you will output day/month/year and on others month/day/year according to your country/language settings.

Right, now let's add in some script to call the subroutine.


@echo off

:show_date
call :get_date
echo Date: %_date%
goto eof

:get_date
for /F "tokens=2 delims= " %%d in ('date /T') do (
set _date=%%d
)
goto blackhole

:eof
echo Press any key to quit...
pause > NUL
goto blackhole

:blackhole

Calling the subroutine is done in much the same way as calling an external batch but with an extra colon: call :get_date. This sets the %_date% variable which can then be shown from within the calling routine.

Note the importance of the 'goto blackhole' instruction at the end of the subroutine, this is what makes you 'return' to the calling code. You can alternatively use goto:EOF or goto :EOF. (Note that this is NOT the same as goto eof without the colon, which leads to the "Press any key" section of this script.)

One way to improve our subroutine would be to add arguments to allow for various date formats.

Thoughts?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory