'Holding a formula with variables inside another variable
I decided I wanted to beautify my batch code by assigning a formula (which contains its own sub-variables ('hrs' and 'min' and 'sec') as well as numerical operations and math operators) to a variable ('myformula') at the top of my code, then call and expand the variable (%myformula%) later on in multiple "set /a ..." commands.
I have tried %%hrs%% and !hrs! and ^carets, as well as !myformula!, but I always get a "Missing operand." error. This suggests to me that the maths operators are not being expanded correctly, or that to numerical values are being converted to characters.
I should add that everything works perfectly if I admit defeat, and replace %myformula% in the code with the actual formula.
Screen output gives correct display of the formula -
My Formula : %hrs%*60*60*100+%min%*60*100+%sec%*100+%cen%
Missing operand.
My Time :
( OR - My Time : 1 depending on %, %%, !, ^, etc, etc ... )
Can anyone suggest how to make the formula expansion %myformula% work correctly?
(I would consider NON native solutions such as - use javascript, use cscript, use powershell - as well as defeatest answers like - "set /a mytime=the+original+formula" - as not being an answer to my real question).
@echooff
SETLOCAL ENABLEDELAYEDEXPANSION
:start
set myformula=%hrs%*60*60*100+%min%*60*100+%sec%*100+%cen%
:timer
rem - Timer code credits go to - rberteig (2014)
rem Convert t0 into a scaler in 100th of sec with no
seperator chars.
set /a t0=%time: =0%
set /a hrs=1%t0:~0,2%-100
set /a min=1%t0:~3,2%-100
set /a sec=1%t0:~6,2%-100
set /a cen=1%t0:~9,2%-100
echo My Formula : %myformula%
set /a mytime=%myformula%
rem - set /a mytime=!myformula! - does not work either.
echo My Time : %mytime%
:finish
pause
ENDLOCAL
exit /B 0
:EOF
Solution 1:[1]
Ok, with lots more trial and error, I found the solution myself. When saving formula (which is intended for arithmetic evaluation) to a variable, no % character wrapping is required.
This is apparently because the SET coomand, when used with the /A switch, automatically assumes any alphabet characters to be variables, and expands them without requiring any % wrapping.
This is alluded to in the SET /? help topic, and is mentioned a bit more in various web pages and forums. The only example I could find in retrospect was -
Thus the answer to my question is to use this code line when seting the "myformula" variable:
:start
set myformula=hrs*60*60*100+min*60*100+sec*100+cen
which expands perfectly as intended at the later code line:
set /a mytime=%myformula%as its preceding and proceeding echo lines prove from their screen output.
Who would have thought???
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ken White |
